我如何将其更改为循环和数组表示法?

时间:2015-04-05 04:19:18

标签: javascript arrays forms loops

我在form1中有4个名为txtParent的文本框。这是我要问的最后一个if语句。在允许表单提交之前,用户必须填写每个文本框。我怎么能把它改成一个循环和数组,但仍然按照它应该如何工作?

<html>
<head>
<title>Field Trip Consent Form</title>

<script type="text/javascript">

function validates() { 
var radioChecked = false;
var moMonth = document.getElementById("getMonth").value;
var moDay = document.getElementById("getDay").value;

for(var i=0; i< document.form1.permission.length; i++) {

if(document.form1.permission[i].checked) {
      radioChecked = true;          
    }
}
if(radioChecked == false) {      
    alert("Please chose permission Status");
    return false;          
} 
if(document.form1.destination.value == "") {
    alert("Please type in the Destination textbox");   
    return false;     
}   

if(moMonth == 'Month') { 
    alert("Please select a Month"); 
    return false; 
}   
if(moDay == 'Day') { 
    alert("Please select a Day"); 
    return false;
}   
if(document.form1.txtParent.value == "") {
    alert("Please type in the txtParent textbox");    
    return false;            
}
return true;        
}
</script> 
</head>
<body>
<h1>Field Trip Consent Form</h1>

<form name="form1" onsubmit="return validates()" method='post' 
 action="http://legacy.jefferson.kctcs.edu/users/mark.prather/formhandler.asp"> 

<form>

<h2>Description of Trip</h2>
<p>Destination &nbsp;

<input type="text" name="destination" SIZE="50" /></p>
<p>Date of Trip &nbsp;
<select name="month" id='getMonth'>
<option selected value="Month">Month</option>
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
<option value="May">May</option>
<option value="Jun">Jun</option>
<option value="Jul">Jul</option>
<option value="Aug">Aug</option>
<option value="Sep">Sep</option>
<option value="Oct">Oct</option>
<option value="Nov">Nov</option>
<option value="Dec">Dec</option>
</select>
<select name="day" id='getDay'>
<option selected value="Day">Day
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>

<select name="year">
<option selected value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>

<h2>Parental Information</h2>
<p>Mother's Name &nbsp;
<input type="text" name="txtParent" size="20" /></p>
<p>Mother's Work Phone &nbsp;
<input type="text" name="txtParent" size="20" /></p>
<p>Father's Name &nbsp;
<input type="text" name="txtParent" size="20" /></p>
<p>Father's Work Phone &nbsp;
<input type="text" name="txtParent" size="20" /></p>

<p><input type="radio" name="permission" value="yes" /> Permission is Granted &nbsp;
<input type="radio" name="permission" value="no" /> Permission is NOT Granted &nbsp;</p>

<p><input type="submit" value="Submit This Data" /> &nbsp; &nbsp; 
<input type="reset" /></p> 
</form>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

嗯,试试这个。

setInterval(function(){
    if (document.form1.txtParent.value != "") {
      alert('TextBox is full')
       return true;
    }
   },1)

我想你也可以在文本改变时执行脚本。

你也可以使用jQuery:

$( "txtParent" ).change(function() {
  alert( "Changed!" );
});

答案 1 :(得分:0)

如果您只是尝试循环并验证所有txtParent元素,那么

document.getElementsByTagName将返回与该名称匹配的所有DOM元素。

   var inputs = document.getElementsByName("txtParent");
    for(var i  =0, len = inputs.length; i < len; i++) {
        if(inputs[i].value === "") {
             alert("Your error message here");
             return false;
        }
    }

如果您想在[]中使用txtParent表示法,那么

您的HTML将成为:

<h2>Parental Information</h2>
<p>Mother's Name &nbsp;
<input type="text" name="txtParent[]" size="20" /></p>
<p>Mother's Work Phone &nbsp;
<input type="text" name="txtParent[]" size="20" /></p>
<p>Father's Name &nbsp;
<input type="text" name="txtParent[]" size="20" /></p>
<p>Father's Work Phone &nbsp;
<input type="text" name="txtParent[]" size="20" /></p>

在JS中:

document.querySelectorAll("[name='txtParent[]']")

这会返回一个NodeList。因此,您需要迭代并检查字段是否为空。

var inputs = document.querySelectorAll("[name='txtParent[]']");
for(var i  =0, len = inputs.length; i < len; i++) {
    if(inputs[i].value === "") {
         alert("Your error message here");
         return false;
    }
}

答案 2 :(得分:0)

我建议先稍微更改一下HTML,以便为每个<input>元素指定一个唯一的名称;否则,在服务器端,提交的最后一个值可能会覆盖所有其他值(尽管如果你想要一个数组,你可以简单地将[]附加到名称上):

<form action="#" method="post">
  <h2>Parental Information</h2>
  <p>Mother's Name &nbsp;
    <input type="text" name="mothersName" size="20" />
  </p>
  <p>Mother's Work Phone &nbsp;
    <input type="text" name="mothersPhone" size="20" />
  </p>
  <p>Father's Name &nbsp;
    <input type="text" name="fathersName" size="20" />
  </p>
  <p>Father's Work Phone &nbsp;
    <input type="text" name="fathersPhone" size="20" />
  </p>
  <button>Submit</button>
</form>

我假设在您的实际项目中,您已将表单元素包装在<form>元素中,并提供了一些提交该表单的方法;但为了演示的目的,我在这里添加了这些。

至于JavaScript,我建议:

// a named function to perform the checks:
function validate(event) {
  // 'event' and 'this' are passed in automagically from
  // the addEventListener() used later.

  // here we prevent the default action (form submission):
  event.preventDefault();

  // caching the 'this' in case we need to use it again:
  var self = this,
    // retrieving the <input> elements of the <form> (the 'this')
    // using document.querySelectorAll(), and a CSS selector:
    textInputs = this.querySelectorAll('input[type=text]'),

    // converting the NodeList to an Array, using
    // Array.prototype.slice() and Function.prototype.call():
    textInputArray = Array.prototype.slice.call(textInputs, 0),

    // filtering that array to find the <input> elements
    // whose value (after removing leading/trailing white-space)
    // is equal to an empty string:
    empties = textInputArray.filter(function(input) {
      // removing the 'invalid' class-name from all <input> elements:
      input.classList.remove('invalid');

      // keeping only those elements for which the assessment
      // returns true:
      return input.value.trim() === '';
    });

  // iterating over the empties (the array of empty-value
  // <input> elements):
  empties.forEach(function(input) {
    // adding the 'invalid' class:
    input.classList.add('invalid');

    // leaving a message (to the console, not an alert()),
    // using the nodeValue (text) of the <input>'s previous sibling,
    // after removing leading/trailing white-space and converting
    // it to lower-case:
    console.log("Please enter " + input.previousSibling.nodeValue.trim().toLowerCase());
  });
}

// getting the first (or no) <form> element from the document,
// and assigning the named function as the event-handler for the
// submit event:
document.querySelector('form').addEventListener('submit', validate);

function validate(event) {
  event.preventDefault();
  var self = this,
    textInputs = this.querySelectorAll('input[type=text]'),
    textInputArray = Array.prototype.slice.call(textInputs, 0),
    empties = textInputArray.filter(function(input) {
      input.classList.remove('invalid');
      return input.value.trim() === '';
    });

  empties.forEach(function(input) {
    input.classList.add('invalid');
    console.log("Please enter " + input.previousSibling.nodeValue.trim().toLowerCase());
  });
}

document.querySelector('form').addEventListener('submit', validate);
.invalid {
  background-color: rgba(255, 0, 0, 0.3);
}
<form action="#" method="post">
  <h2>Parental Information</h2>
  <p>Mother's Name &nbsp;
    <input type="text" name="mothersName" size="20" />
  </p>
  <p>Mother's Work Phone &nbsp;
    <input type="text" name="mothersPhone" size="20" />
  </p>
  <p>Father's Name &nbsp;
    <input type="text" name="fathersName" size="20" />
  </p>
  <p>Father's Work Phone &nbsp;
    <input type="text" name="fathersPhone" size="20" />
  </p>
  <button>Submit</button>
</form>

我还会进一步更改您的HTML,以便将标签文本正确关联到相关的<input>元素,并将<input>个元素组关联在一起,以表示彼此之间的关系:

<form action="#" method="post">
  <h2>Parental Information</h2>
  <!-- using the fieldset element to group associated form fields
       together -->
  <fieldset>
    <!-- the legend element provides a title for that 'group'
         of elements -->
    <legend>Mother</legend>
    <label>Mother's Name &nbsp;
      <input type="text" name="mothersName" size="20" />
    </label>
    <label>Mother's Work Phone &nbsp;
      <input type="text" name="mothersPhone" size="20" />
    </label>
  </fieldset>
  <fieldset>
    <legend>Father</legend>
    <label>Father's Name
      <input type="text" name="fathersName" size="20" />
    </label>
    <label>Father's Work Phone &nbsp;
      <input type="text" name="fathersPhone" size="20" />
    </label>
  </fieldset>
  <button>Submit</button>
</form>

function validate(event) {
  event.preventDefault();
  var self = this,
    textInputs = this.querySelectorAll('input[type=text]'),
    textInputArray = Array.prototype.slice.call(textInputs, 0),
    empties = textInputArray.filter(function(input) {
      input.classList.remove('invalid');
      return input.value.trim() === '';
    });

  empties.forEach(function(input) {
    input.classList.add('invalid');
    console.log("Please enter " + input.previousSibling.nodeValue.trim().toLowerCase());
  });
}

document.querySelector('form').addEventListener('submit', validate);
.invalid {
  background-color: rgba(255, 0, 0, 0.3);
}

label {
  display: block;
}

fieldset {
  margin: 0 0 0.5em 0;
}
<form action="#" method="post">
  <h2>Parental Information</h2>
  <fieldset>
    <legend>Mother</legend>
    <label>Mother's Name &nbsp;
      <input type="text" name="mothersName" size="20" />
    </label>
    <label>Mother's Work Phone &nbsp;
      <input type="text" name="mothersPhone" size="20" />
    </label>
  </fieldset>
  <fieldset>
    <legend>Father</legend>
    <label>Father's Name
      <input type="text" name="fathersName" size="20" />
    </label>
    <label>Father's Work Phone &nbsp;
      <input type="text" name="fathersPhone" size="20" />
    </label>
  </fieldset>
  <button>Submit</button>
</form>

参考文献: