当复选框处于活动状态时,jQuery禁用其他行中的输入

问题描述 投票:0回答:1

我想在选中复选框时启用/禁用输入。我的网站中有很多部分具有相同的结构,所以我知道我需要使用

this

施工。我试图做这样的事情,但它不起作用。有人可以帮帮我吗?

$('.component-other').on('click', function(){
    var isChecked = $(this).is(':checked');
    if (isChecked) {
        $(this).closest('.row').find('.component-other-value').prop("disabled", false);
    } else {
        $(this).closest('.row').find('.component-other-value').prop("disabled", true);
    }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="container">
  <div class="row">
    <div class="col-sm-12">
      <label for="sause-oth">Other</label>
      <input type="checkbox" name="sause" id="sause-oth" class="enable component-other">
    </div>
  </div>
  <div class="row input-row">
    <div class="col-sm-12">
      <input type="text" name="sause-other" id="sause-other" class="component-other-value" disabled="disabled" placeholder="Type text here">
    </div>
  </div>
</div>
</section>
<section>
  <div class="container">
  <div class="row">
    <div class="col-sm-12">
      <label for="sause-oth">Other</label>
      <input type="checkbox" name="sause" id="sause-oth-1" class="enable component-other">
    </div>
  </div>
  <div class="row input-row">
    <div class="col-sm-12">
      <input type="text" name="sause-other" id="sause-other-1" class="component-other-value" disabled="disabled" placeholder="Type text here">
    </div>
  </div>
</div>
</section>
javascript jquery html
1个回答
1
投票

最接近的.row是不够的。你必须再为DOM增加一层。

$('.component-other').on('click', function(){
    $(this).closest('.container')
           .find('.component-other-value')
           .prop("disabled", !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <div class="container">
    <div class="row">
      <div class="col-sm-12">
        <label for="sause-oth">Other</label>
        <input type="checkbox" name="sause" id="sause-oth" class="enable component-other">
      </div>
    </div>
    <div class="row input-row">
      <div class="col-sm-12">
        <input type="text" name="sause-other" id="sause-other" class="component-other-value" disabled="disabled" placeholder="Type text here">
      </div>
    </div>
  </div>
</section>
<section>
  <div class="container">
    <div class="row">
      <div class="col-sm-12">
        <label for="sause-oth">Other</label>
        <input type="checkbox" name="sause" id="sause-oth-1" class="enable component-other">
      </div>
    </div>
    <div class="row input-row">
      <div class="col-sm-12">
        <input type="text" name="sause-other" id="sause-other-1" class="component-other-value" disabled="disabled" placeholder="Type text here">
      </div>
    </div>
  </div>
</section>
© www.soinside.com 2019 - 2024. All rights reserved.