[英]Button disable unless both input fields have value
我的頁面上有一個帶有兩個輸入字段和一個提交按鈕的表單,我希望具有禁用“提交”按鈕的功能,直到兩個輸入字段上都有值。 當且僅當在兩個字段中都輸入了值時,該按鈕才是可點擊的。
如何用 js 和 jQuery 實現這個?
這是我的頁面:
<html>
<body>
<form method=post>
<input type=text id='first_name'>
<input type=text id='second_name'>
<input type=submit value=Submit>
</form>
</body>
</html>
我想同時擁有 js 和 jQuery 解決方案
這是使用 jQuery 的解決方案:
HTML(請注意,我在提交按鈕中添加了一個 id):
<form method=post>
<input type="text" id="first_name">
<input type="text" id="second_name">
<input type="submit" value="Submit" id="submit" disabled>
</form>
JavaScript/jQuery:
$(':text').keyup(function() {
if($('#first_name').val() != "" && $('#second_name').val() != "") {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
工作示例:http: //jsfiddle.net/nc6NW/1/
jQuery: jQuery 禁用/啟用提交按鈕
純JS:
<html>
<body>
<form method="POST"
onsubmit="return this.first_name.value!='' && this.second_name.value!=''">
<input type="text" id="first_name" name="first_name"
onkeyup="this.form.subbut.disabled = this.value=='' || this.form.second_name.value==''">
<input type="text" id="second_name" name"second_name"
onkeyup="this.form.subbut.disabled = this.value=='' || this.form.first_name.value==''">
<input type="submit" value="Submit" disabled="disabled">
</form>
</body>
</html>
不要忘記表單字段的name
屬性!
<html>
<head>
<script type="text/javascript" src="path.to/jquery.js" />
<script type="text/javascript">
$(function() { // on document load
var fn = function() {
var disable = true;
$('#myForm input[type:text]').each(function() { // try to find a non-empty control
if ($(this).val() != '') {
disable = false;
}
});
$('#myForm input[type:submit]').attr('disabled', disable);
}
$('#myForm input[type:text]').change(fn); // when an input is typed in
fn(); // set initial state
});
</script>
<body>
<form id="myForm" method="POST">
<input type="text" id="first_name">
<input type="text" id="second_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
$(function(){
$("#first_name, #second_name").bind("change keyup",
function(){
if($("#first_name").val() != "" && $("#second_name").val() != "")
$(this).closest("form").find(":submit").removeAttr("disabled");
else
$(this).closest("form").find(":submit").attr("disabled","disabled");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.