我的页面上有一个带有两个输入字段和一个提交按钮的表单,我希望具有“提交”按钮处于“禁用”状态的功能,直到两个输入字段上都有值为止。当且仅当两个字段中都输入了值时,该按钮才可单击。 如何用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 解决方案
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/
事件监听器版本
window.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('myForm');
// this is a little overkill
form.addEventListener('submit', (e) => {
let name1 = form.first_name.value.trim();
let name2 = form.second_name.value.trim();
if (name1 === "" || name2 === "") e.preventDefault(); // stop submission
});
form.addEventListener('input', (e) => {
let name1 = form.first_name.value.trim();
let name2 = form.second_name.value.trim();
document.getElementById('subbut').disabled = name1 === "" || name2 === "";
});
});
<form method="POST" id="myForm">
<input type="text" id="first_name" name="first_name" />
<input type="text" id="second_name" name "second_name" />
<input id="subbut" type="submit" value="Submit" disabled="disabled" />
</form>
纯 HTML 版本
<form method="POST">
<input type="text" id="first_name" name="first_name" required />
<input type="text" id="second_name" name "second_name" required />
<input name="subbut" type="submit" value="Submit" />
</form>
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>