[英]jquery .prop('disabled', true) not working
我试图使用复选框在<input type="text">
上切换disabled = true|false
。 我能够获得输入的值,但我无法将输入设置为禁用。
我的jquery / js代码
<script>
$(function () {
$('.date').datepicker();
$('body').on('change', '.housing', function () {
if ($(this).val() == 'dorms') {
$(this).parent().next(".dorms").show();
} else {
$(this).parent().siblings(".dorms").hide();
}
});
$('body').on('change', '.single', function () {
if ($(this).checked) {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").val(''); // does not empty the input
$(this).prev(".roommate").disabled = true; // does not set to disabled
$(this).prev(".roommate").prop('disabled', true); // does not set to disabled
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
} else {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").disabled = false; // always stays false
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
}
});
});
</script>
我的HTML代码
<div class="registration_housing particpant_0" data-sync="0">
<div>
<label class="particpant_0"></label>
</div>
<div>
<label>Off Campus (not included)</label>
<input type="radio" name="housing[0]" value="none" class="housing" />
</div>
<div>
<label>On Campus</label>
<input type="radio" name="housing[0]" value="dorms" class="housing" />
</div>
<div class="dorms" style="display:none;">
<div>
<label>Checkin:</label>
<input type="text" name="check_in[0]" class="date" />
</div>
<div>
<label>Checkout:</label>
<input type="text" name="check_out[0]" class="date" />
</div>
<div>
<label>Roommate:</label>
<input type="text" name="roommate[0]" class="roommate" />
<input type="checkbox" name="roommate_single[0]" value="single" class="single" />check for singe-occupancy</div>
</div>
<div class="line">
<hr size="1" />
</div>
</div>
<div>
<label id="echo1"></label>
</div>
<div>
<label id="echo2"></label>
</div>
你可以在http://jsfiddle.net/78dQE/1/看到这个
知道为什么我能得到(".roommate")
的价值 - 即。 $(this).prev(".roommate").val()
但
$(this).prev(".roommate").disabled = true;
要么
$(this).prev(".roommate").prop('disabled', true);
不会将(".roommate")
为禁用?
您的问题是将jquery与DOM元素属性混合在一起
更改if ($(this).checked) {
to if (this.checked) {
用jquery你会做的
$(this).is(':checked') // But you could just do this.checked
和
$(this).prev(".roommate").prop('disabled', false); // or $(this).prev(".roommate")[0].disabled = false;
代替
$(this).prev(".roommate").disabled = false;
所以你可能需要这个:
$('body').on('change', '.single', function () {
$(this).prev(".roommate").prop('disabled', this.checked).val('');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.