Louis Tran
Louis Tran

Reputation: 1156

Javascript: How can I get all value of selected checked checkboxes, push to an array then put in in a input HTML element?

I have a list of 50 checkboxes. If users check some of them, how can I get all values of the selected ones and push them into an array then place it in a hidden text element?

Can I use the same name for all checkboxes? or I must use different name for each of them?

<input type="checkbox" name="bulk_id[]" value="1"/>
<input type="checkbox" name="bulk_id[]" value="2"/>
<input type="checkbox" name="bulk_id[]" value="3"/>
<input type="checkbox" name="bulk_id[]" value="4"/>
<input type="checkbox" name="bulk_id[]" value="5"/>
...

Thank you.

Upvotes: 2

Views: 3233

Answers (2)

Mahmoud Zakal
Mahmoud Zakal

Reputation: 128

so you have to get all checkboxes you have

 var checkboxes = document.getElementsByName("bulk_id[]");
 var arrayVal = [];
 for (var i= 0; i<checkboxes.length;i++)
  {
     if (checkboxes[i].checked === true)
     {
         arrayVal.push(checkboxes[i].value); 
     }
  }

Upvotes: 0

WKx
WKx

Reputation: 411

You tagged your question with jquery, so i'll assume you are using it.

You select checkbox with input[type=checkbox] and use the subclass :checked to filter checked ones

1- get all checked boxes in an array

var selectedValues =[]
$('input[type=checkbox]:checked').each(function(i,e){
  selectedValues.push( $(e).attr('value') )
})

2- append the content of this array in a hidden input (separated by ,)

$('#yourhiddenID').val( selectedValues.join(',') );

In this solution the name of your checkboxes does not matter.

Put your checkboxes in a container for a better selection :

$('#yourCheckboxContainerID input[type=checkbox]:checked')

Upvotes: 1

Related Questions