0

I am defining an array of checked checkboxes:

<script>
var all_checked = new Array();
function add_checked(checked_checkbox_id)
{
all_checked.push(checked_checkbox_id);
}

<html>
<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(?????);" />
</html>

So my question is how to pass the checked checkbox ID to the function to append to the global

all_checked

variable

1

3 Answers 3

2

Pass this in your function and then use it to get the id property:

HTML

<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(this);" />

JavaScript

var all_checked = new Array();
function add_checked(el) {
    all_checked.push(el.id);
}

Remember, this will push the id to the array no matter what, whether the box is checked or unchecked, even if the id already exists in the array.

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Use this keyword by passing to yout function.

 onclick="add_checked(this)";

Here you can the id as

this.id

then in

function add_checked(checked_checkbox) {
  all_checked.push(checked_checkbox.id);
}

FYI: script tag should be within html tag

Comments

0

HTML:

<button onclick="send_query(document.getElementsByTagName('input'))">

function send_query(check) {

    var values = [];
    for (i = 0; i < check.length; i++) {
        if (check[i].checked == true) {
            values.push(check[i].value);
        }
    }
    console.log(values.join());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.