如何验证元素是否存在于表单中或不使用JS

时间:2011-02-27 07:59:11

标签: javascript validation

<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error


//Don't write individual validation
//check element is exist or not if exist check for validation

//I need know how to check an element is exist or not
</script>

<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*

</pre>

3 个答案:

答案 0 :(得分:2)

向他们申请class

<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />

并且像这样:

function validate(){
  var elms = document.getElementsByTagName('input');

  for (var i = 0; i < elms.length; i++){
    if (elms[i].className === 'txt'){
      if (elms[i].value === ''){
          alert('Make sure to fill in all required fields');
          // now focus it
          elms[i].focus();
          return false;
      }
    }
  }

  return true;
}

然后像这样调用上面的函数:

<form ............ onsubmit="return validate();">

答案 1 :(得分:2)

发布您的代码。

最简单的验证方法是使用jquery validate plugin。(为什么在其他人做同样的情况下编写自己的代码?)。

示例

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    $("#feedbackform").validate();
  });
</script>

<body>
<form id = "feedbackform" method = "POST" action = "">
 <h3><span>Contact Us</span></h3>
 <fieldset>
  <legend>Contact form</legend>

  <label for="id_name">Name *</label>
  <input id="id_name" class="required" type="text" name="name" />

  <label for="id_email">Email</label>
  <input id="id_email" type="email" name="email" class="email"/>

  <label for="id_comments">Message *</label>
  <textarea id="id_comments" class="required" name="comments"></textarea>
  <button type="submit">Send</button>       

 </fieldset>        
</form>

要验证的元素添加class =“required”。我希望提供的例子是自我解释的

答案 2 :(得分:1)

您可以获取对元素的引用并检查引用是否为null:

for (var i=1; i<=100; i++) {
  var elem = document.getElementById('txtbox' + i);
  if (elem != null) {
    ...
  }
}

另一种方法是查看表单中的元素,但是您需要一种方法来访问表单:

var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
  var elem = elems[i];
  if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
    ...
  }
}