如果输入值为空,我想检查一个表单,但我不确定最好的方法,所以我尝试了这个:
使用Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
HTML:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
有人有想法或更好的解决方案吗?
答案 0 :(得分:6)
添加required
属性是现代浏览器的绝佳方式。但是,您很可能也需要支持旧版浏览器。这个JavaScript将:
required
输入(在提交的表单中)是否已填写。alert
属性,则仅提供required
行为。JavaScript:
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
请务必将this
添加到checkform函数中,无需检查未提交的inputs
。
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
答案 1 :(得分:2)
根据您计划支持的浏览器,您可以使用HTML5必需属性并放弃JS。
<input name="promotioncode" id="promotioncode" type="text" required />
答案 2 :(得分:1)
演示:http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
说明: