简体   繁体   中英

Disabling checkbox when a select menu has values

I have a select menu with about four options. The first option of the select menu has NO value. The other options have values. When a user selects an option that has a value, I need the checkbox disabled, otherwise, if they go back to the option with the blank value, the checkbox is re-enabled.

The code below successfully disables the checkbox, BUT I want the checkbox to be re-enabled when the user clicks on the first blank option of the select menu.

$(document).ready(function(){
$('#select-menu').change(function() {
  if ($(this).val() !== ':first-child') { 
        $("#related-checkbox").attr("disabled", true);
  } else {
    $("#related-checkbox").attr("disabled", false);
            }
});
});

The statement says

if ($(this).val() !== ':first-child') { 

literally checks if selected value string is 'first-child', not whether it is the first child. Just set it to blank

if ($(this).val() !== '') { 

If you want to check whether it is the first option (not whether it is blank) then you can compare the first child's val to the selected element's val

if ($(this).val() == $(this).children(':first-child').val())

您的意思是说:“当用户点击选择菜单的第一个空白选项时,我希望重新启用该复选框。”?

$("#related-checkbox").removeAttr("disabled");

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