Assigning checkbox values to variables

2.5k views Asked by At

I've got a list of possible checkboxes and the user can select up to three options. What I'm struggling with is how to recognize which boxes are checked, and then assign them to variables (to send in a later ajax call). So far the code I've written seems to just take the first three checkbox values regardless of whether they are checked or not and use those in my ajax call. Please help me figure out where I've gone wrong.

Here's my HTML:

<ul id="Names" class="stateNames">
    <li>Alabama
        <ul class="airports">
            <li><input type="checkbox" class="destination"/> Birmingham, AL</li>
            <li><input type="checkbox" class="destination"/> Huntsville, AL</li>
        </ul>
    <li>Alaska
        <ul class="airports">
            <li><input type="checkbox" class="destination"/> Anchorage, AK</li>
            <li><input type="checkbox" class="destination"/> Fairbanks, AK</li>
            <li><input type="checkbox" class="destination"/> Juneau, AK</li>
        </ul>
    </li>
</ul>
<input type="button" onclick="clickHandler()" value="Submit" />

Here's my javascript/jquery:

function clickHandler() {
endLocDest1 = "";
endLocDest2 = "";
endLocDest3 = "";

for(i = 0; i < document.getElementsByClassName('destination').length; i++) {
    if (document.getElementsByClassName('destination')[i].checked) {
        endLocDest1 = document.getElementsByClassName('destination')[0].value;
        endLocDest2 = document.getElementsByClassName('destination')[1].value;
        endLocDest3 = document.getElementsByClassName('destination')[2].value;
    }
    alert(endLocDest1 + endLocDest2 + endLocDest3);
};
}

I've also put this code into a fiddle http://jsfiddle.net/6ywm1n6h/3/ (which currently doesn't return anything).

Thanks in advance!

2

There are 2 answers

1
rfornal On BEST ANSWER

In your jsfiddle, you had jQuery turned on, assuming that, try using ...

$(".destination:checked")

Which will return all checked; you can use this as an array and determine which are clicked.

EDIT: You can assign this to a variable, say ...

var checked_values = $(".destination:checked");

... then loop through and do what you need.

for (var i=0,len=checked_values.length; i<len; i++) {
  console.log(checked_values[i].attr("id"));
}
2
Maug Lee On

If your code is wrapped in <form> and </form> then checked inputs will be sent automatically when form is submitted (normaly or AJAX'ed). Your mistake is that you do not set names nor values to your checkboxes. Try:

<input type="checkbox" name="airport[alabama][]" value="Birmingham">
<input type="checkbox" name="airport[alabama][]" value="Huntsville">
<input type="checkbox" name="airport[alaska][]" value="Anchorage">
<input type="checkbox" name="airport[alaska][]" value="Fairbanks">

and see print_r($_POST) or print_r($_GET) (depending on your form method) in page which receives form submission.