[英]Validating Mandatory Input Boxes Using Javascript only
I wanted to know what would be the best method to validate (to ensure that all 4 of the input boxes are not blank)? 我想知道验证的最佳方法是什么(以确保所有4个输入框都不为空)?
<html>
<head></head>
<body>
<input type="text" id="i1">
<input type="text" id="i2">
<input type="text" id="i3">
<input type="text" id="i4">
</body>
</html>
If they are all to be input
s then you can use document.getElementsByTagName
如果全部
input
则可以使用document.getElementsByTagName
var allinputs = document.getElementsByTagName("input");
console.log(allinputs);
for (var i = 0; i < allinputs.length; i++) {
if(allinputs[i].value.length == 0){
alert('need to have something here');
return;
}
}
here is a working fiddle 这是一个工作的小提琴
JQuery Validate is an really easy way to validate your fields. JQuery Validate是验证字段的一种非常简单的方法。 You can read more about it at their wiki:
您可以在他们的Wiki上阅读有关它的更多信息:
http://docs.jquery.com/Plugins/Validation http://docs.jquery.com/插件/验证
HTML: HTML:
<input type="button" value="submit" onclick="submitForm()">
JavaScript : JavaScript:
function submitForm()
{
if(validate())
{
alert('No blank found!!');
}
else
{ alert('blank found!!'); }
}
function validate()
{
var i1 =document.getElementById('i1').value;
var i2 =document.getElementById('i2').value;
var i3 =document.getElementById('i3').value;
var i4 =document.getElementById('i4').value;
var result = false;
if( i1 && i2 && i3 && i4) {
result = true;
}
return result;
}
My custom method, not cross-browser: 我的自定义方法,不是跨浏览器:
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
var allChecked = document.querySelectorAll('input[type=text]').every(function(el) {
return el.value !== '';
});
if (allChecked) alert("All checked!");
The cross-browser (IE8 and above), not funny way: 跨浏览器(IE8及更高版本),不是很有趣的方式:
var inputs = document.querySelectorAll('input[type=text]');
var allChecked = true;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].value === '') {
allChecked = false;
}
}
if (allChecked) alert("All checked!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.