简体   繁体   中英

Enable/disable text box on check/uncheck box

I have a checkbox that is enabled by default.

The issue here is that once i uncheck it, it remains disabled even when i check it back again.

<input type="checkbox" class="show-check" checked value="1" id="DisplayOnClick">

document.getElementById("DisplayOnClick").onclick = function(){
        if(document.getElementById("DisplayOnClick").checked){
            document.getElementById("myFieldset").style.display = "block";

        } else {       
            document.getElementById("myFieldset").disabled = !this.checked;          
        }
    }

Also tried this following code but this doesn't do anything.

$(function () {

        $("#DisplayOnClick").click(function () {
            if ($(this).is("checked")){
                $("#myFieldset").show();
            }else {
                $("#myFieldset").hide();
            }
        });
    });

I am not sure what i am doing wrong here. Any help is appreciated. Thank you.

$(function () {

$("#DisplayOnClick").change(function () {
    if ($(this).is(":checked")){
            $("#myFieldset").removeAttr('disabled')
        }else {
            $("#myFieldset").attr('disabled', 'true')   
        }
    });
});

This should do what you want.

The selector for the checkbox needs to be :checked

Also a thing I ran into with fieldsets it would seem, is that even if you set disabled=false , it's still disabled. It doesn't care what the value of disabled is, only that it exists.

Just doing the following worked for me.

document.getElementById("DisplayOnClick").onclick = function(){
 document.getElementById("myFieldset").disabled = !this.checked;
}

look at is checked if it is checked then show the fieldset else hide.

 $('#DisplayOnClick').click((e) => $('#myfieldset')[$(e.target).is(':checked') ? 'show' : 'hide']()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" class="show-check" checked value="1" id="DisplayOnClick"> <div id="myfieldset"> hello from my field set </div> 

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