我一直在 Stack 上查看一些帖子,试图让一个简单的表单验证工作,但它所做的只是禁用了我的提交按钮。它的目的是在他们在输入字段中输入文本后删除禁用。
到目前为止
Jquery
$('input:submit').attr('disabled',true);
$('input').change(function(){
if($('input').val() != ''){
$('input:submit').attr('disabled',true);
} else {
$('input:submit').removeAttr('disabled');
});
HTML
<form action="send.php" method="post">
<input id="name" name="name" type="text" required placeholder="Name"/>
<input id="email" name="email" type="email" required placeholder="Enter a valid email address"/>
<input name="submit" id="subscribe" type="submit" value="Subscribe for free"/>
</form>
最佳答案
您应该使用添加到所有必需字段的类来查找每个输入。如果用户更改其中之一并且仍然没有输入,则按钮保持禁用状态:
jQuery:
$('input.required').change(function(){
if($(this).val() != ''){
$(this).removeClass('required',true);
}else{
$(this).addClass('required',true);
}
//check the length to enable or disable submit
if($(".required").length == 0){
$('#subscribe').attr('disabled',false);
}else{
$('#subscribe').attr('disabled',true);
}
});
html:
<form action="send.php" method="post">
<input id="name" name="name" type="text" class="required" placeholder="Name" />
<input id="email" name="email" type="email" class="required" placeholder="Enter a valid email address" />
<input name="submit" id="subscribe" type="submit" value="Subscribe for free" />
</form>
但是请记住,此解决方案仅适用于启用 JavaScript 的情况。
关于javascript - Jquery 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17941779/