使用Javascript检查html表单值是否为空
我想检查表单的输入值是否为空,但我不确定最好的方法,因此我尝试了以下方法: Javascript:使用Javascript检查html表单值是否为空,javascript,html,Javascript,Html,我想检查表单的输入值是否为空,但我不确定最好的方法,因此我尝试了以下方法: Javascript: function checkform() { if (document.getElementById("promotioncode").value == "") { // something is wrong alert('There is a problem with the first field'); retur
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
<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>
html:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
<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>
有人有什么想法或更好的解决方案吗?根据您计划支持的浏览器,您可以使用HTML5 required属性并放弃JS
<input name="promotioncode" id="promotioncode" type="text" required />
添加
required
属性是现代浏览器的一个好方法。但是,您很可能还需要支持较旧的浏览器。此JavaScript将:
- 验证是否填写了每个
必需的
输入(在提交的表单中)
- 仅当浏览器不支持
属性时,才提供required
行为警报
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;
}
演示:
说明:
- 要停止提交过程,请使用event.preventDefault。Event是传递给函数onsubmit Event的参数。它可以是html或addeventlistner格式
- 要开始提交,您必须停止并阻止执行默认值李>
- 您可以通过仅重新调整false来中断forEach循环。不使用中断;与正常循环一样
- 我把id数组放在这里,你可以把元素的名称放在这里,这个论坛会检查它们是否为空
- FindInput方法只需遍历form元素的子元素,并查看它们的id是否已在id数组中找到。如果是,则将该元素添加到输入中,然后在提交之前检查输入中是否有值。如果没有,则调用“防止默认”
required
属性应该可以做到这一点……除此之外,我建议使用DOM方法而不是内联属性附加处理程序。