我有以下标记:
$(document).ready(function(){
$('#template').on('change', function() {
var $option = $('option:selected', this); // get selected option
var optgroup = $option.closest('optgroup').attr('data-customer-type-id');
$('#winback').disabled = (optgroup != "2");
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<!-- other elements -->
<div class="form-group">
<label for="template">Email Template</label>
<select class="form-control" name="template" id="template" required="required">
<optgroup label="Customer" data-customer-type-id="1">
<option>opt1</option>
</optgroup>
<optgroup label="Former Customer" data-customer-type-id="2">
<option>opt2</option>
</optgroup>
<optgroup label="Propsect" data-customer-type-id="3">
<option>opt3</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="winback">Cancellation Date</label>
<input type="date" class="form-control" id="winback" name="winback" disabled="disabled" required="required" />
</div>
<!-- ... -->
</form>
我希望如果我在第二个optgroup
中选择了一个选项,那么它将启用ID为winback
的输入,否则如果我在任何其他{{1}中选择了一个选项它将禁用输入。但相反,每当我选择新的optgroups
时,根本不会发生任何事情。它永远不会启用,它只会保持禁用状态。
然而,奇怪的是,如果我使用option
检查我的 optgroup 变量的值,那么该值就是我期望的值。
答案 0 :(得分:3)
属性disabled
未在jquery对象上公开。你应该改变
$('#winback').disabled = (optgroup != "2");
到
$('#winback').prop('disabled', (optgroup != "2"));
答案 1 :(得分:0)
您需要使用.prop( propertyName, value )
你可以做到
$('#winback').prop("disabled", optgroup != "2");
检查完整代码。
$(document).ready(function(){
$('#template').on('change', function() {
var $option = $('option:selected', this); // get selected option
var optgroup = $option.closest('optgroup').attr('data-customer-type-id');
$('#winback').prop("disabled", optgroup != "2");
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<!-- other elements -->
<div class="form-group">
<label for="template">Email Template</label>
<select class="form-control" name="template" id="template" required="required">
<optgroup label="Customer" data-customer-type-id="1">
<option>opt1</option>
</optgroup>
<optgroup label="Former Customer" data-customer-type-id="2">
<option>opt2</option>
</optgroup>
<optgroup label="Propsect" data-customer-type-id="3">
<option>opt3</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="winback">Cancellation Date</label>
<input type="date" class="form-control" id="winback" name="winback" disabled="disabled" required="required" />
</div>
<!-- ... -->
</form>