0

I have three checkboxes with common name

<input type="checkbox" name="checkBox[]" id="checkBox" value="1">
<input type="checkbox" name="checkBox[]" id="checkBox" value="2">
<input type="checkbox" name="checkBox[]" id="checkBox" value="3">

And jquery to push the selected checkbox value into an array before I pass that array to ajax

var data = {'checkBox[]': []};
$(":checked").each(function () 
{
    data['checkBox[]'].push($(this).val());
});

I am able to iterate through the checkBox array in PHP in the Ajax page but failing on the client side.

checkBox.length is not giving me the number of checkboxes I've checked. I am unable to find out whether an array is an empty array. I have tried - if (checkBox === undefined || checkBox.length == 0) but got no result. How can I find the length for the above array and whether it is an empty array. I do not want to pass an empty array to the ajax url.

1
  • Note on your HTML: Your checkboxes should have different id values, or just omit the id. Ids are supposed to be unique across a page. Commented Apr 29, 2015 at 3:07

4 Answers 4

3

Unclear what you are looking for, but to get length of array you are building inside data object use:

var len = data['checkBox[]'].length;

Note: as currently shown in you sample code data is object with one property named "checkbox[]" with array as value, possibly you were looking for something else, maybe data = {checkbox:[]} or just checkbox=[];

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

1 Comment

Working like charm. Thank you really so much. var len = data['checkBox[]'].length gives me the total number of checkbox I've checked in the form. Thank you really so much :)
1

change your code into this

var checkBox = [];
$("input[type=checkbox]:checked").each(function() {
checkBox.push($(this).val());
});

console.log(checkBox.length);

Comments

0

Your question is really unclear. If you are looking to get a count of the number of checkboxes you have checked you can try $('checkbox[name="checkbox[]"]:checked').length;

Comments

0

Another option:

data['checkBox[]'] = $('input[name="checkBox[]"]:checked').map(function() {
    return $(this).val();
});

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.