dimanche 13 décembre 2015

Pass multiple checkbox values to dropdown lists in jQuery

I have a checkbox with 5 options. Only two of these can be selected. What I am trying to do is pass the value checked to a dropdown list. Since two checkboxes can be selected, I would like their values to be passed to two dropdown lists. Here's what I have so far.

HTML

<input class="theme" type="checkbox" name="theme" value="adventure" id="adventure"/><label for="adventure">Adventure</label>
<input class="theme" type="checkbox" name="theme" value="attraction" id="attraction"/><label for="attraction">Attraction</label>
<input class="theme" type="checkbox" name="theme" value="culture" id="culture"/><label for="culture">Culture</label>
<input class="theme" type="checkbox" name="theme" value="leisure" id="leisure"/><label for="leisure">Leisure</label>
<input class="theme" type="checkbox" name="theme" value="nature" id="nature"/><label for="nature">Nature</label>

<select id="list2">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>

<select id="list1">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>

jQuery

$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
    if($(this).attr("value")=="adventure"){
        $("#list1").val("adventure");
    }
    if($(this).attr("value")=="attraction"){
        $("#list2").val("attraction");
    }
    if($(this).attr("value")=="culture"){
        $(".cultureInterests").toggle();
    }
    if($(this).attr("value")=="leisure"){
        $(".leisureInterests").toggle();
    }
    if($(this).attr("value")=="nature"){
        $(".natureInterests").toggle();
    }
});

As you can see, this method is faulty as the order of selecting a checkbox is beyond my control and I won't be able to tell where to pass the value. Any help is highly appreciated.

Thank you so much!




Aucun commentaire:

Enregistrer un commentaire