3

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;
        }
5
  • 9
    why all of your checkboxes have the same id? this is invalid html Commented Aug 3, 2012 at 7:39
  • @freefaller: Never heard of that before. Do you have a link which explains this in detail? 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 Commented Aug 3, 2012 at 7:45
  • @Aaron and Torsten... ack, many many apologies - yes, you are completely correct, I was thinking about the name attribute. I will remove my comment (which as it's not there, incorrectly states that you can use id="contact_id[]") 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. Commented Aug 3, 2012 at 7:50

3 Answers 3

3

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');
Sign up to request clarification or add additional context in comments.

5 Comments

Better if you put the example code into your answer, as well as leaving your jsfiddle live demo (as there's no guarantee the link will still be active in the future)
Give me a sec. Thanks for the friendly suggestion!
Thanks for your answer. I have this code for Select all options and it works fine. How can I apply it to checkboxes? var opts = document.querySelectorAll("#groups1\\[\\] option"), groups = [].map.call(opts, function(option) { if (option.selected) { return "groups[]=" + option.value; } }).filter(Boolean).join("&");
So this question is solved? I kindly suggest you make a new question and close this.
Not yet, the above code in my comment showed how I passed selected options from a Select, as an array. I am asking is it possible to apply the same code on checkboxes?
1

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/

Comments

0
$(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">

1 Comment

It helps to store a checkbox values as a single variable values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.