使用JavaScript检查表单中的所有元素 [英] Check all elements in form with Javascript

查看:66
本文介绍了使用JavaScript检查表单中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开始时就了解javascript,但是有问题.

I know javascript in the beginning level, but I have a problem.

我在表单中有 7 个输入元素,我希望将其全部填写. 我想出了这个主意,但它看起来令人作呕.

I have 7 input elements in a form and I want all of them to be filled. I came up with this idea but it looks disgusting.

有人可以帮我检查是否填写了所有表单元素?

function validateForm()
{
var x=document.forms["register"]["name"].value;
var y=document.forms["register"]["phone"].value;
var z=document.forms["register"]["compname"].value;
var q=document.forms["register"]["mail"].value;
var w=document.forms["register"]["compphone"].value;
var e=document.forms["register"]["adres"].value;
var r=document.forms["register"]["zip"].value;
if (x==null || x=="" || y==null || y=="" || z==null 
|| z=="" || q==null || q=="" ||  w==null || w=="" || e==null || e=="" 
|| r==null || r=="")
{
alert("Please fill all the inputs");
return false;
}
}
</script>

推荐答案

这是简单且肮脏的方式.

This is the simple and dirty way.

一种更好的方法是更新一条验证消息,说明该字段是必填字段.

A better way is to update a validation message that the fields are required.

function validateForm()
{
  var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]

  var i, l = fields.length;
  var fieldname;
  for (i = 0; i < l; i++) {
    fieldname = fields[i];
    if (document.forms["register"][fieldname].value === "") {
      alert(fieldname + " can not be empty");
      return false;
    }
  }
  return true;
}

这篇关于使用JavaScript检查表单中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆