我想在选中复选框时启用/禁用输入。我的网站中有很多部分具有相同的结构,所以我知道我需要使用
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>
最接近的.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>