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.

3 answers

  • answered 2018-10-11 19:13 SpeedOfRound

    $(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.

  • answered 2018-10-11 19:28 ace23

    Just doing the following worked for me.

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

  • answered 2018-10-11 19:31 Bryan Dellinger

    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>