-1

I am looking for a better solution to achieve the subject.

  • When a checkbox is clicked, disable select box and enable input field and vise versa. my code is

       <div class="col-md-4 col-lg-4">
        <select class="form-control recipe_cats otherrecipe_cat" id="recipe_cats" name="recipe_cats">
        <option value="-1">Books Category</option>
        <option value="30" class="level-0">Book1</option>
        <option value="48" class="level-0">Book2</option>
        <option value="49" class="level-0">Book3</option>
        </select>
        </div>
    
        <div class="col-md-3 col-lg-3">
        <label class="control-label checkbox-inline" for="lblothercats">Not Listed</label> <sup><i class="fa fa-asterisk"></i></sup>
        <input class="form-control" type="checkbox" name="lblothercats" id="lblothercats" value="option1">
        <span class="help-block"></span>
        </div> <!-- /.form-group -->
    
    
        <div class="col-md-4 col-lg-4">
        <label class="control-label" for="otherrecipe_cat">Other Category</label> <sup><i class="fa fa-asterisk"></i></sup>
        <input type="text" class="form-control otherrecipe_cat" name="otherrecipe_cat" id="otherrecipe_cat" value="" role="input" aria-required="true" disabled="disabled" />
        <span class="help-block"></span>
        </div><!-- /.form-group -->
    

and my current code is

$('#lblothercats').change(function () {
    if (this.checked) {
        $('input.otherrecipe_cat').removeAttr('disabled');
        $('select.recipe_cats').attr('disabled', 'disabled');
    } else {
        $('select.recipe_cats').removeAttr('disabled');
        $('input.otherrecipe_cat').attr('disabled', 'disabled');
    }
}).trigger('change');

This works fine, but I am wondering if there is any better option or solution to achieve this? I will be writing many segments like this.

Regards

Satpal
  • 132,252
  • 13
  • 159
  • 168
user1305063
  • 67
  • 1
  • 5

1 Answers1

2

This works fine, but I am wondering if there is any better option or solution to achieve this?

You can improve like:

$('#lblothercats').change(function () {
    $('select.recipe_cats').prop('disabled', this.checked);
    $('input.otherrecipe_cat').prop('disabled', !this.checked);
}).trigger('change');

You should use .prop() instead of .attr(), Go through .prop() vs .attr()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168