[英]Disable form submit button input=text and input=checkbox with jquery
我有一个带有三个输入的表单( [type=text]
,多个输入[type=checkbox]
和一个禁用的提交按钮)。 如果用户已填写所有三个文本输入并至少选中了一个复选框,我希望启用提交按钮。
我发现这个小提琴在所有三个文本输入上都很好用,但是我想添加一个附加条件,即必须至少选中一个复选框:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
在复选框中添加class="checkbox"
,然后将checkEmpty()
修改为此:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
然后单击添加事件,复选框为:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
嘿,仅在jquery部分中添加输入[type = checkbox],这是您所需的输出,请尝试以下代码:Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
好吧,我现在有一个严重的问题。 我正在使用wordpress并添加:
<?php wp_head(); ?>
<?php wp_footer(); ?>
对于我的header.php和footer.php,因为我需要它们,所以插件正在加载。 自从我添加了它们以来,Stephan Sutter的工作解决方案不再起作用。 如果我填写所有必填表格,则提交按钮仍处于禁用状态。 如果我删除它们,它将再次起作用,但是我需要它们作为插件。
我认为这是因为插件将输入文本添加到页面中。 有什么方法可以将代码frm Stephan用于已定义的表单ID =#addmovie-form?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.