【问题标题】:How would I change this to Loop and Array Notation?我如何将其更改为循环和数组表示法?
【发布时间】:2023-04-08 00:03:01
【问题描述】:

我在名为 txtParent 的 form1 中有 4 个文本框。这是我要问的最后一个 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>

【问题讨论】:

  • 您的form 标签和/或submit 按钮在哪里?

标签: javascript arrays forms loops


【解决方案1】:

如果您只是想循环并验证所有 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;
    }
}

【讨论】:

  • 我想说你的第一个答案实际上回答了我的问题,所以谢谢你mohamedrias!
【解决方案2】:

嗯,试试这个。

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

我想您也可以在文本更改时执行脚本。

你也可以使用 jQuery:

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

【讨论】:

    【解决方案3】:

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

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

    我假设,在您的实际项目中,您已将表单元素包装在 &lt;form&gt; 元素中,并提供了一些提交该表单的方法;但出于演示的目的,我在此处添加了这些内容。

    至于 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 以将标签文本正确关联到相关的 &lt;input&gt; 元素,并将 &lt;input&gt; 元素组关联在一起以表示它们之间的关系:

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

    参考资料:

    【讨论】:

    • 感谢您提供的所有信息!我会看看它,它可能会在以后帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多