Check the box for "Select Value" using jQuery

I am after a small jQuery script that will check the corresponding checkbox depending on what value is selected in the Select input element.

eg. If the value 'PJ Gallagher Drummoyne' is selected in select#CAT_Custom_70944, then it is checked input#drummoyne-list.checkbox. The same applies to all options in the selection list:

  • '' PJ Gallagher Drummein will check input#drummoyne-list.checkbox
  • 'PJ Gallagher Parramatta checks input#parramatta-list.checkbox
  • "Union Hotel North Sydney" checks input#union-list.checkbox

Has anyone seen something like this before? Sample HTML code:

<div class="item">
    <label for="CAT_Custom_70944">Preferred GMH Hotel <span class="req">*</span></label><br />
    <select name="CAT_Custom_70944" id="CAT_Custom_70944" class="cat_dropdown">
        <option value=" " selected="selected">- Please Select -</option>
            <option value="P.J. Gallagher Drummoyne">P.J. Gallagher Drummoyne</option>
        <option value="P.J. Gallagher Parramatta">P.J. Gallagher Parramatta</option>
        <option value="Union Hotel North Sydney">Union Hotel North Sydney</option>
    </select>
</div>
<div class="item">
    <input type="checkbox" id="drummoyne-list" class="checkbox" name="CampaignList_20320" /> <label>Subscribe to: P.J. Gallagher Drummoyne Newsletter</label>
</div>
<div class="item">
    <input type="checkbox" id="parramatta-list" class="checkbox" name="CampaignList_20321" /> <label>Subscribe to: P.J. Gallagher Parramatta Newsletter</label>
</div>
<div class="item">
    <input type="checkbox" id="union-list" class="checkbox" name="CampaignList_20322" /> <label>Subscribe to: The Union Hotel Newsletter</label>
</div>
+3
source share
3 answers

jQuery . , , , "drummoyne", "parramatta" "union", .

, , .

$(function(){
  $('select.cat_dropdown').change(function(){
     $('.item :checkbox').removeAttr('checked'); //uncheck the other boxes
     $('.item :checkbox')[this.selectedIndex-1].checked = true;
  });
});
+3

, "change" , .

.

$("select#CAT_Custom_70944").change( function() {
    var val = this.value;
    if (val == "P.J. Gallagher Drummoyne") {
        // Code to check correct box...
    } else if (val == "P.J. Gallagher Parramatta") {
        // Code to check correct box...
    } else {
        // Code to check correct box...
    }
}
+1

, - , , " "? .

Thus, no jQuery code is required at all.

+1
source

Source: https://habr.com/ru/post/1709831/


All Articles