最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Pass all checkboxes values as an array in Javascript - Stack Overflow

programmeradmin5浏览0评论

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;
        }

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;
        }
Share Improve this question edited Aug 3, 2012 at 7:47 Usman 3,2783 gold badges30 silver badges49 bronze badges asked Aug 3, 2012 at 7:36 alkhaderalkhader 1,0086 gold badges17 silver badges33 bronze badges 5
  • 9 why all of your checkboxes have the same id? this is invalid html – devmiles. Commented Aug 3, 2012 at 7:39
  • @freefaller: Never heard of that before. Do you have a link which explains this in detail? – Aaron Digulla Commented Aug 3, 2012 at 7:40
  • @freefaller id's must be unique. You are probably referring to the name attribute. davidwalsh.name/checkbox-form-input-arrays – Torsten Walter Commented Aug 3, 2012 at 7:45
  • @Aaron and Torsten... ack, many many apologies - yes, you are pletely correct, I was thinking about the name attribute. I will remove my ment (which as it's not there, incorrectly states that you can use id="contact_id[]") – freefaller Commented Aug 3, 2012 at 7:46
  • @Torsten Walter , the idea is that I have a list of contacts and there are checkbox for each contact. The value for each check box is "contact_id" which been taken from database. – alkhader Commented Aug 3, 2012 at 7:50
Add a ment  | 

3 Answers 3

Reset to default 3

http://jsfiddle/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 remend 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/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./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">
发布评论

评论列表(0)

  1. 暂无评论