0

How to pass this kind of HTML input to JavaScript so that it recognizes these array values?

<input type="checkbox" id="collection[]" value="0">
<input type="checkbox" id="collection[]" value="1">
<input type="checkbox" id="collection[]" value="2">]

The only idea I have (never played with js this way, tbh) is to reach it through:

$("#collection").val();

But I got undefined error. I have no other idea how to make javascript recognize that variable collection is an array and has to passed as such.

Thanks in advance!

Sates
  • 408
  • 1
  • 5
  • 21
  • What is it that you are trying to do? Decide which checkboxes are checked? – taylorcressy Jun 15 '14 at 15:07
  • Sorry, didn't change name to id. Doesn't work either. @taylorcressy: I'm trying to pass values of selected checkboxes to json and then, through jQuery, to a php file so that only selected checkboxes are processed. But I need javascript to recognize which checkboxes to pass... – Sates Jun 15 '14 at 15:08
  • 2
    You cannot have duplicate IDs, change it to name – Shaunak D Jun 15 '14 at 15:11
  • 1
    See http://stackoverflow.com/questions/19529443/jquery-get-input-array-field – JustcallmeDrago Jun 15 '14 at 15:12

3 Answers3

1

You cannot have Duplicate Ids. Though duplicate IDs will give you desired output in this case, it is invalid to use them for multiple elements.

<input type="checkbox" name="collection[]" value="0">
<input type="checkbox" name="collection[]" value="1">
<input type="checkbox" name="collection[]" value="2">

There are many ways you can access array based elements.

jQuery .map(): Alternative is .each()

Demo

$("[name='collection[]']").map(function(){return $(this).val();}).get()

Working Demo for checking checked inputs. To get the checked checkbox,

$('input').change(function () {
    console.log($("[name='collection[]']:checked").map(function () {
        return $(this).val();
    }).get());
});
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
1

Remember, IDs need to be unique within your document. So set by 'name' not by id.

You can use

$('#someid').is(":checked");

for individually checking each checkbox, or loop through them with a jQuery selector

To loop through them set

<input type="checkbox" name="checkboxes" value="0">
<input type="checkbox" name="checkboxes" value="1">
<input type="checkbox" name="checkboxes" value="2">

Then with jQuery,

$('input[name=checkboxes]:checked').each(function(i, e) {
        e.val();   //The value of the checkbox that is selected
});
taylorcressy
  • 966
  • 8
  • 23
0
$("#collection")

It mean's ,"Find me an element which id's equal collection on page" , of course it can't find anything. You can use .each function and you can use checkboxes attributes. For example ;

var myCheckBoxArray = []

$("input[type='checkbox']").each(function(i,elm){
    myCheckBoxArray.push(elm);
});
ugursogukpinar
  • 327
  • 1
  • 5