简体   繁体   中英

How to select a select box option if a check box is checked

I am currently running into an issue with selecting a selectbox option if a checkbox is checked. I only have two options in my selectbox with the values of yes and no. If the checkbox is checked, the option with the value of "yes" should be selected. If it is not checked, then "no" will be selected. My code is simply not working and I cannot understand why. Below is my code. Any help would be greatly appreciated, thank you.

<select id="slctbox">
    <option value="no">No</option>
    <option value="yes">Yes</option>
</select>

<input type="checkbox" id="chkbox"/>

$("#chkbox").click(function() {
    if($("#chkbox").is(':checked')) {
        $("#slctbox option[value=yes]").prop("selected", true);
    } else {
        $("#slctbox option[value=no]").prop("selected", true);
    }
});

Your code seems to work fine. Have you checked for simple mistakes like forgetting the jquery script tag or to wait for it to load before attaching the handler?

On a side note, I would personally use

$('#chkbox').change(function() {
    if($("#chkbox").is(':checked')) {
        $("#slctbox").val("yes");
    } else {
        $("#slctbox").val("no");
    }
});

which relies on setting the value rather than searching for an element and setting an attribute.

See: http://jsfiddle.net/9ZLe4/1/

if you're looking for more compact:

$('#chkbox').change(function(){
    $('#slctbox').val(this.checked ? 'yes' : 'no');
});

(thanks Johan for making it just a little bit shorter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM