javascript - 如果输入为空,如何防止提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10516122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How prevent submit if input are empty with javascript
提问by Shaoz
I have a login form but I wanna check if the fields are empty then do not submit. I did `return false' on submit but the browser still loads a new page. How can I stop that?
我有一个登录表单,但我想检查这些字段是否为空,然后不要提交。我在提交时做了`return false',但浏览器仍然加载一个新页面。我怎么能阻止呢?
JS:
JS:
var username = document.getElementById('usernameField');
var password = document.getElementById('passwordField');
var loginBtn = document.getElementById('loginBtn');
var infoBox = document.getElementById('formInfo');
var isEmpty = /^\s*$/;
var addEventTo = function(id, type, fn, capture) {
if (document.addEventListener) {
id.addEventListener(type, fn, capture);
} else {
id.attachEvent('on'+type, fn);
}
};
function checkIfAllEmpty() {
var loginForm = document.getElementById('loginform'),
allInputs = loginForm.getElementsByTagName('input'),
max = allInputs.length,
i;
for (i = 0; i < max; i++) {
if (allInputs[i].type !== 'submit') {
if (allInputs[i].match(isEmpty)) {
infoBox.innerHTML = 'All your fields are empty';
return false;
}
}
}
}
//addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
if (document.addEventListener) {
loginBtn.addEventListener('submit', checkIfAllEmpty, false);
} else {
loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
}
HTML:
HTML:
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
</form>
Many thanks
非常感谢
回答by Vosobe Kapsimanis
If it ok to go with html5 (works fine with newer versions of Safari, Chrome, Firefox, Opera > 11.00 but no IE as usual), you can add the required tag in your input field.
如果可以使用 html5(适用于较新版本的 Safari、Chrome、Firefox、Opera > 11.00,但不能像往常一样使用 IE),您可以在输入字段中添加所需的标签。
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label>
<input type="text" placeholder="Enter username" id="usernameField" required />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label>
<input type="password" placeholder="Enter password" id="passwordField" required />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
回答by Naama Katiee
Looks like the event listener of the onsubmit are not being added correctly, anyway the easiest way to do it is to add onsubmit="return someValidationFuncThatReturnTrueOrFalse()" in your form:
看起来 onsubmit 的事件侦听器没有正确添加,无论如何最简单的方法是在表单中添加 onsubmit="return someValidationFuncThatReturnTrueOrFalse()" :
<form id="loginForm" method="post" action="#" onsubmit="return validate()">
can I ask why you're using this approach on your js code? it could be done much easily if your form is static ...
我能问一下你为什么在你的 js 代码上使用这种方法吗?如果您的表单是静态的,则可以轻松完成...
function validate() {
if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
alert("all fields are empty");
return false;
} else {
return true;
}
}
or something like that ...
或类似的东西 ...
回答by Arka Dev
I use Prototype (as a javascript framework) and this code should work:
我使用 Prototype(作为 javascript 框架),这段代码应该可以工作:
js:
js:
function checkEmpties() {
var usr = $('username');
var pass = $('pass');
var frm = $('formId');
if (usr.value && pass.value) {
//frm.submit();
alert('submit');
} else {
alert('failed');
}
}
Event.observe(window, 'DomReady', function() {
var btn = $('submitBtn');
Event.observe('submitBtn', 'click', checkEmpties);
}
html:
html:
<form id="formId">
<input type="text" name="username" id="username" />
<input type="password" name="pass" id="pass" />
<input type="button" id="submitBtn" value="Send" />
</form>
What it does: Once the document has loaded attaches an event observer to the button, so when it's clicked the function checkEmpties is called. This function will retrieve the value of the inputs and if they're not empty, submit the form.
它的作用:一旦文档加载完毕,就会将一个事件观察器附加到按钮上,所以当它被点击时,函数 checkEmpties 被调用。此函数将检索输入的值,如果它们不为空,则提交表单。
Hope it helps
希望能帮助到你
回答by Onheiron
You can use the attribute disabled="disabled" for the form inputs :
您可以将属性 disabled="disabled" 用于表单输入:
http://www.w3schools.com/tags/att_input_disabled.asp
http://www.w3schools.com/tags/att_input_disabled.asp
set the submit button as disabled, then add an onchange listener to each input field so that if every field is filled you remove the disable attribute and the user can subit the form.
将提交按钮设置为禁用,然后向每个输入字段添加一个 onchange 侦听器,这样如果每个字段都已填写,则删除禁用属性,用户可以提交表单。