简体   繁体   中英

Disable or enable checkbox on dropdown selection

I have a drop-down with some entries and a checkbox.

If I've selected the 2nd entry in my drop-down, the checkbox should be enabled. Otherwise, it should be disabled and unchecked. I don't know how to deal with this.

This is what I got:

function checkSelected() {
    if (("#test").prop('selectedIndex') === 2) {
        //disable and uncheck
    } else {
        //enable
    }
}

HTML:

<select id="test">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

<input id="test2" type="checkbox" name="test2">

Bind change event to SELECT element and the use .prop( propertyName, value ) to manipulate properties.

 $('#test').on('change', function() { if ($(this).prop('selectedIndex') === 2) { $('#test2').prop('disabled', true).prop('checked', false); } else { $('#test2').prop('disabled', false) } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="test"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <input id="test2" type="checkbox" name="test2"> 

here is my solution.

First we disable the checkbox programmatically, then we watch for that value being selected and enable or disable the properties as per requirements.

Please let me know if this solves your issue!

 var elem = $("#test2"); elem.attr("disabled", true); elem.change(function(){ if($(this).val() === "saab"){ elem.attr("disabled", false); }else{ elem.attr("disabled", true); elem.attr('checked', false); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="test"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <input id="test2" type="checkbox" name="test2"> 

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