Jquery:启用一个表单域并在单击复选框时禁用其他

时间:2014-05-18 18:50:07

标签: 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</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 () {
    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');

这很好用,但我想知道是否有更好的选择或解决方案来实现这一目标?我会写很多这样的片段。

此致

1 个答案:

答案 0 :(得分:2)

这很好用,但我想知道是否有更好的选择或解决方案来实现这个目标?

您可以改进:

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

您应该使用.prop()代替.attr(),浏览.prop() vs .attr()

相关问题