簡體   English   中英

如何將其更改為循環和數組表示法?

[英]How would I change this to Loop and Array Notation?

我在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>

嗯,試試這個。

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

我想您也可以在更改文本時執行腳本。

您也可以使用jQuery:

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

如果您只是試圖遍歷並驗證所有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;
    }
}

我建議先稍微改變一下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元素包裝在一個<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> 

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM