使用Required属性对所有字段进行Javascript验证 [英] Javascript Validation for all field with Required attribute

查看:284
本文介绍了使用Required属性对所有字段进行Javascript验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个问题的答案,但无法在任何地方找到它。

I've searched high and low for the answer to this but can't find it anywhere.

我有一个具有HTML'required'属性的表单并且它在提交之前突出显示需要填写的字段做得很好......或者可以做到,但是我的表格用螺栓固定到的系统(我无法控制)在几秒钟后仍然提交表格。它依赖于Javascript的提交。因此,我想编写一个Javascript脚本来检查所有属性的所有字段。目前我有一个脚本,它指定了我想要强制的字段,但如果它可以查找属性,那就太棒了。

I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.

推荐答案

如果使用输入[type = submit] ,则不需要任何JavaScript

In case that input[type=submit] is used, you don't need any JavaScript

<form id="theForm" method="post" acion="">
  <input type="firstname" value="" required />
  <input type="lastname" value="" required />
  <input type="submit" name="submit" value="Submit" />  
</form>

工作 jsBin

但如果输入[type = button] 用于提交表单,使用下面的代码段

But if input[type=button] is used for submitting the form, use the snippet below

<form id="theForm" method="post" acion="">
  <input type="firstname" value="" required />
  <input type="lastname" value="" required />
  <input type="button" name="button" value="Submit" />  
</form>

window.onload = function () {
  var form = document.getElementById('theForm');
  form.button.onclick = function (){
    for(var i=0; i < form.elements.length; i++){
      if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
        alert('There are some required fields!');
        return false;
      }
    }
    form.submit();
  }; 
};

Wotking jsBin

这篇关于使用Required属性对所有字段进行Javascript验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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