Search code examples
javascriptjqueryhtmlcheckboxnested-checkboxes

Assigning checkbox values to variables


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!


Solution

  • 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"));
    }