Sol Sol - 4 months ago 11
HTML Question

With JQuery how can you make an array of inputs from checkboxes into one variable?

I would like to make the data from this jquery submit go into one variable that I can put into html. I am using the append button to add html to my form, but can't figure out how to make the

data
variable into an array of each check box value .

https://jsfiddle.net/soljohnston777/k5yc1y2a/2/

JQuery:

$(".checkboxadd").click(function(){
$('[id^="add_policies_checkbox"]').each(function(i, v){
//alert(this.value);
if($(v).prop('checked')){
var data=$(v).val();
$("#div_to_add_this_checkbox_value").append("<input type=hidden name='pnpID_instructions' value=\'"+data+"\' />P&P #'s: "+data+"");}
});
});//end ajaxifypolicies


HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1"/>
<input type="checkbox" value="2" id="add_policies_checkbox2"/>
<input type="checkbox" value="3" id="add_policies_checkbox3"/>
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>
<div> Check mark all 3 then hit submit, What I want is the output like an array:<br>P&P #'s:1,2,3 <br> (and the hidden value="1,2,3")
</div>

Kld Kld
Answer

To convert an array to you can use array.join(',').

$(".checkboxadd").click(function() {
var data = [];
$('[id^="add_policies_checkbox"]').each(function(i, v) {  
  if ($(v).prop('checked')) {
    data.push($(v).val());
  }
});
console.log(data);

$("#div_to_add_this_checkbox_value").html('P&P #s:' + data.join(',') + "<input type='hidden' name='pnpID_instructions' value='"+data.join(',')+"' />");


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="add_policies_checkbox1" />
<input type="checkbox" value="2" id="add_policies_checkbox2" />
<input type="checkbox" value="3" id="add_policies_checkbox3" />
<button class="checkboxadd">Submit</button>
<div id="div_to_add_this_checkbox_value"></div>

Comments