skip to Main Content

I am trying to develop a JQuery script to change the state of a checkbox by setting the disabled attribute to true depending on the state of a different checkbox.

I have three checboxes – suspended, option1 and option2

Using the below code, thn clicking the suspended checkbox, the other two are disabled. If I uncheck the suspended box, they are then availble (disabled attr removed).

I would like to apply the same logic atpage load. My code is below:

(function( $ ) {
    'use strict';

    $( document ).ready(function() {
        if( $('input[name="suspended"]').is(':checked')){
            console.log( "Suspended is checked" );
            $('input[name="option1"]' ).attr("disabled", true);
            $('input[name="option2"]' ).attr("disabled", true);
        }
        else{
            console.log( "Suspended is unchecked" );
            $('input[name="option1"]' ).removeAttr("disabled");
            $('input[name="option2"]' ).removeAttr("disabled");

        }

        $( 'input[name="suspended"]' ).change( function( e ){
            e.preventDefault;
            if ($(this).is(':checked')) {
                $('input[name="option1"]' ).attr("disabled", true);
                $('input[name="option2"]' ).attr("disabled", true);
            }else {
                $('input[name="option1"]' ).removeAttr("disabled");
                $('input[name="option2"]' ).removeAttr("disabled");
            }option2
            
        } );

    });

})( jQuery );

I have obviously solved the change state of click situation, but canno’t work out why it doesnt not also work on page load. I am able to get a concole.log message to display the state at page load, but chnage the state of the checboxes.

2

Answers


  1. I can see that you like JQuery, but even in vanilla JavaScript it doesn’t have to be complicated. Instead of doing all the tests you can just give the disabled property the value of the checked property on the checkbox.

    I like using <fieldset> and it could make sense in this case, because you have more than one input element that you would like to disable.

    document.addEventListener('DOMContentLoaded', e => {
      let form = document.forms.form01;
      form.options.disabled = form.suspended.checked;
    });
    
    document.forms.form01.suspended.addEventListener('change', e => {
      e.target.form.options.disabled = e.target.checked;
    });
    fieldset {
      border: none;
      display: flex;
      flex-direction: column;
    }
    <form name="form01">
      <label><input type="checkbox" name="suspended">Suspended</label>
      <fieldset name="options">
        <label>Option 1:<input type="text" name="option1"></label>
        <label>Option 2:<input type="text" name="option2"></label>
      </fieldset>
    </form>

    And here, the jQuery version:

    $(document).ready(function() {
      $('[name="options"]').prop('disabled', $('[name="suspended"]').prop('checked'));
    });
    
    $('[name="suspended"]').change(function(e) {
      $('[name="options"]').prop('disabled', $(e.target).prop('checked'));
    });
    fieldset {
      border: none;
      display: flex;
      flex-direction: column;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <form name="form01">
      <label><input type="checkbox" name="suspended">Suspended</label>
      <fieldset name="options">
        <label>Option 1:<input type="text" name="option1"></label>
        <label>Option 2:<input type="text" name="option2"></label>
      </fieldset>
    </form>
    Login or Signup to reply.
  2. @chrwahl has already provided some very good points in his answer. However, you could go even a little further by making the script shorter and at the same time applicable for a whole range of fieldsets:

    $(function(){ // when DOM is loaded ...
       $(".suspended").change(function() {
      $(this).closest("fieldset").find("input").not(this).prop('disabled', $(this).prop('checked'));
    }).change();
    });
    fieldset {
      border: none;
      display: flex;
      flex-direction: column;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <form name="form01">
      <fieldset>
        <label><input type="checkbox" class="suspended" name="cb1">Suspended</label>
        <label>Option 1:<input type="text" name="option1"></label>
        <label>Option 2:<input type="text" name="option2"></label>
      </fieldset>
      <fieldset>
        <label><input type="checkbox" class="suspended" name="cb1" checked>Suspended</label>
        <label>Option 3:<input type="text" name="option3"></label>
        <label>Option 4:<input type="text" name="option4"></label>
      </fieldset>
    </form>

    The same can of course also be done in a Vanilla JavaScript way:

    function upd8inps(cb){
     cb.closest("fieldset").querySelectorAll("input:not(.suspended)").forEach(el=>el.disabled=cb.checked)
    }
    
    document.addEventListener('DOMContentLoaded',()=>{
     document.querySelector("form")
      .addEventListener("change",ev=>{
       if(ev.target.classList.contains("suspended")){
       upd8inps(ev.target);
      }});
     document.querySelectorAll("fieldset .suspended").forEach(upd8inps);
    });
    fieldset {
      border: none;
      display: flex;
      flex-direction: column;
    }
    <form name="form01">
      <fieldset>
        <label><input type="checkbox" class="suspended" name="cb1">Suspended</label>
        <label>Option 1:<input type="text" name="option1"></label>
        <label>Option 2:<input type="text" name="option2"></label>
      </fieldset>
      <fieldset>
        <label><input type="checkbox" class="suspended" name="cb1" checked>Suspended</label>
        <label>Option 3:<input type="text" name="option3"></label>
        <label>Option 4:<input type="text" name="option4"></label>
      </fieldset>
    </form>

    Admittedly, the vanilla version is slightly longer. I have chosen to use a delegated event listening here on the form element. This way even dynamically added fieldsets will respond to a change of their .suspended checkbox, if available.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search