简体   繁体   中英

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.

<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />

I need to pass them to one ajax request as array as below:

xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);

I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this

contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5

I have done this as follows

function getContacts(){
            var contacts = document.myform.contact_id, ids = [];
            for (var i = 0; i < contacts.length; i += 1){
                if (contacts[i].checked)
                     ids.push(contacts[i].value);
            }
            return ids;
        }

http://jsfiddle.net/xQezt/

Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.

First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.

//submit event registration
submitButton.onclick = function () {
    var contactArray = inputsToArray(contacts.children);
    var data = serializeArray(contactArray, 'contact_id[]');
    console.log(data);
}

Then I made your method "getContacts" more generic:

function inputsToArray (inputs) {
    var arr = [];
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked)
            arr.push(inputs[i].value);
    }
    return arr;
}

Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:

function serializeArray (array, name) {
    var serialized = '';
    for(var i = 0, j = array.length; i < j; i++) {
        if(i>0) serialized += '&';
        serialized += name + '=' + array[i];
    }
    return serialized;
}

I also slightly modified your HTML:

<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>

<button id="submit">Submit</button>

Which let me query the DOM like this:

var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');

Your input's id are duplicate. so I recommend you to use name instead of id

For Example, Your HTML will look like this :

<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Then if you want to get the value to querystring then use the JQuery Serialize

$('#contactform').serialize(); 
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5 

jsFiddle : http://jsfiddle.net/Eqb7f/

$(document).ready(function() {
  $("#submit").click(function(){
    var favorite = [];
    $.each($("input[class='check']:checked"), function(){   
      favorite.push($(this).val());
    });
    document.getElementById('fav').value = favorite.join(", ");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="cd-form-list">
  <div>
    <input type="checkbox" id="cd-checkbox-2" class="check" value="A">
    <label for="cd-checkbox-1">A for Apple</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-2" class="check" value="B">
    <label for="cd-checkbox-2">B for Ball</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-3" class="check" value="C">
    <label for="cd-checkbox-3">C for Cat</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-4" class="check" value="D">
    <label for="cd-checkbox-4">D for Dog</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-5" class="check" value="E">
    <label for="cd-checkbox-5">E for Ear</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-6" class="check" value="F">
    <label for="cd-checkbox-6">F for Fish</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-7" class="check" value="G">
    <label for="cd-checkbox-7">G for God</label>
  </div>
  <div>
    <input type="checkbox" id="cd-checkbox-8" class="check" value="H">
    <label for="cd-checkbox-8">H for Hen</label>
  </div>
</div>
<div>
  <input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM