Jquery:单击复选框时启用一个表单字段并禁用另一个表单字段

Jquery:单击复选框时启用一个表单字段并禁用另一个表单字段,jquery,Jquery,我正在寻找一个更好的解决方案来实现这个主题 单击复选框时,禁用选择框并启用输入字段,反之亦然。 我的代码是 <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</op

我正在寻找一个更好的解决方案来实现这个主题

  • 单击复选框时,禁用选择框并启用输入字段,反之亦然。 我的代码是

       <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 -->
    
    这很好,但我想知道是否有更好的选择或解决方案来实现这一点?我会写很多这样的片段

    关于

    这很好,但我想知道是否有更好的选择或解决方案来实现这一点

    您可以通过以下方式进行改进:

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

    你应该使用,而不是,通读

    你所说的多段是什么意思?你能分享你的整个html吗?
    $('#lblothercats').change(function () {
        $('select.recipe_cats').prop('disabled', this.checked);
        $('input.otherrecipe_cat').prop('disabled', !this.checked);
    }).trigger('change');