我一直在尝试添加一个小的jquery功能到一个表单,但似乎不能让它正常运行:
$("#progress-reg").keypress(function(event){
var n = $('#progress-reg').length;
$('#progress-next').prop("disabled", (n < 1) ? true : false);
});
这个想法是,如果用户开始输入#progress-reg
,它将启用#progress-next
按钮(这工作得很好),但如果用户删除#progress-reg的内容,我希望它使按钮恢复为禁用,但上面的代码似乎没有这样做。
我在发帖之前确实在这里搜索了一下,但是没有看到任何东西。
谢谢
您可以使用.on('input',..
事件,它与复制/粘贴一起工作。使用val()
方法获取内容,然后添加或删除按钮的disabled
属性。
$('#progress-next').prop("disabled", true)
// work with copy paste
$("#progress-reg").on('input',function(event){
var n = $(this).val().length;
$('#progress-next').prop("disabled", n < 1)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="progress-reg">
<button id="progress-next">OK</button>
use remove prop disabled if n<1https://api.jquery.com/removeProp/
$("#progress-reg").keyup(function(event){
var n = $(this).val().length;
if (n < 1) $('#progress-next').removeProp("disabled");
else if ($('#progress-next').prop("disabled") == false) $('#progress-next').prop("disabled",true);
});
- 你应该检查输入值的长度,而不是输入本身。
- 你应该绑定
keyup
而不是keypress
。
$("#progress-reg").on("keyup", function(){
var n = this.value.length;
$("#progress-next").prop("disabled", n < 1 ? true : false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="progress-reg" /><button id="progress-next" disabled>Next</button>
您应该检查value
属性的长度
$("#progress-reg").keypress(function(event){
$('#progress-next').prop("disabled", this.value.length == 0);
});
我还重新编写了你的代码一点更短。