skip to Main Content

I need to write a generic jQuery method enable/disable a drop down list based on a checkbox value.

I have 2 components (each has a checkbox and a drop down list) and I don’t want to write the exact same method twice, only with different id’s of the checkbox and the drop down list.

I thought maybe to use the class selector to find the checkboxes (that will have the same class) and somehow go to their parent and search for a drop down list child of that parent (and of course make sure that both of the checkbox and dropdown list will be siblings under the same parent)

2

Answers


  1. Here you can find a working example of a generic jQuery method that uses classes like you asked:

    $('.checkbox-class').on('change', function() {
      let parent = $(this).parent();
      let dropdown = parent.find('.dropdown-class');
      dropdown.prop('disabled', !this.checked);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="component">
      <input type="checkbox" class="checkbox-class">
      <select class="dropdown-class" disabled>
        <option value="option-1">Option 1</option>
        <option value="option-2">Option 2</option>
        <option value="option-3">Option 3</option>
      </select>
    </div>
    Login or Signup to reply.
  2. You’re looking for DOM traversal. If you want to be very generic, technically you don’t need classes or ids, you can just use you elements themself.

    $('input[type=checkbox]').on('change', function() {
      $(this).siblings('select').prop('disabled', !this.checked)
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div>
      <input type="checkbox">
      <select disabled>
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select>
    </div>
    <div>
      <input type="checkbox" checked>
      <select>
        <option>A</option>
        <option>B</option>
        <option>C</option>
      </select>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search