[英]Check if input has specific value
我正在使用 Jquery 检查输入是否具有特定值,如果它确实具有该值,它将启用提交按钮。 问题是我将值设置为 4,但如果输入 44(或以 4 开头的任何内容),它仍会启用按钮。 此外,一旦输入 4,它可以更改为任何内容,并且按钮保持启用状态。
我希望它做的是仅在值为 4 时更改为启用,如果值更改,则应禁用提交按钮。
查询
$(document).ready(function() {
$('#check').keyup(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
}
});
});
HTML
<input id="check" type="text" name="check" />
<input type="submit" name="submit" class="submit" disabled="disabled">
试试这个:
$('#check').change(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
}
else $('.submit').attr('disabled', 'disabled');
});
实际上,当值不是4
时,如果您愿意,您需要重新禁用提交按钮。
更好的是,而不是
$('.submit').attr('disabled', 'disabled');
你可以/应该使用
$('.submit').prop('disabled', true);
所以处理程序变成
$('#check').change(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
}
else $('.submit').prop('disabled', true);
});
甚至更简单
$('#check').change(function() {
$('.submit').prop('disabled', $(this).val() !== '4');
});
它的发生是因为如果值不是 4,你没有禁用按钮。
$('#check').keyup(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
}
else{
$('.submit').attr('disabled','disabled');
}
});
只需添加一个禁用它的 else :)
$(document).ready(function() {
$('#check').keyup(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
} else {
$('.submit').prop('disabled', true);
}
});
});
您需要重新禁用它。
$(document).ready(function() {
$('#check').change(function() {
if($(this).val() === '4') {
$('.submit').removeAttr('disabled');
}else{
$('.submit').prop('disabled');
}
});
使用:
$('#check').keyup(function () {
$('.submit').prop('disabled', $(this).val() !== '4' );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.