javascript - 将验证功能应用于所有文本字段和单选按钮

标签 javascript arrays function

我是 Javascript 新手,不知道如何让我的函数同时适用于单选按钮和文本字段。

下面是表单的 HTML 代码

<form action="sendmail.php" method="post" name="cascader"
 onsubmit="prepareEventHandlers()" id="cascader">   
 <div class="TargetCenter">   <p><strong><span class="asterisk">*</span>Target Center</strong>  </p>
 <label>
   <input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />
   All Countries</label>
 <label>
   <input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />
   France</label>
 <label>
   <input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />
   Bolivia</label>
 <label>
   <input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />
   North America</label>
 <label>
   <input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />
   United Kingdom</label>
 <label>
   <input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />
   Baltics</label>
 <label>
   <input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />
   Slovakia</label>

 <label>
   <input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />
   Sweden</label>

 <label>
   <input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />
   Switzerland</label>
 <br />   </div>  <!--end of Cascade Target-->  <div class="CascadeCategory">    <strong>
 <span class="asterisk">*</span>Cascade Category: </strong>    <label>
  <input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />
  Process</label>    <label>
  <input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />
  Training</label>    <label>
  <input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2"/> Knowledge</label>    <br />     </div> <!--end
  of Cascade Category-->  <div class="ProcessTitle"><strong><span
  class="asterisk">*</span>Process Title:    <input name="textfld"
  type="text" id="processTitle" iname="processTitle"
  onkeypress="checkFieldValue()"  />  </strong><span
  id="errorMessage"></span></div>  <!--end of Process Title-->  <div
  class="CascadeType">    <strong><span class="asterisk">*</span>Cascade
  Type:</strong> <label>   <input type="radio" name="cascadeType"
  value="Release" />   Release</label>    <label>
  <input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />
  Update</label>    <label>
  <input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />
  Reminder</label>    <br /> </div>   <!--end of Cascade Type--> <div class="QuickDescr">    <strong><span class="asterisk">*</span>Quick
 Description: </strong><br /> <br /><textarea name="textfld" cols="70%"
  rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
  </div>   <!--end of Quick Description--> <div class="Details">
  <strong><span class="asterisk">*</span>Details: </strong><br /><br/>
 <textarea name="details" cols="70%" rows="10" id="details"></textarea> </div>
 <!--end of Description--> <div class="DueDate"> <strong><span class="asterisk">*</span>Due
 Date:</strong> <input type="text" class="Due" name="DueDate"
 placeholder="mm.dd.yyyy" />  <span
 class="DueDateFormat">(mm.dd.yyyy)</span></div> <!--end of Due date-->
 <br /> <br /> <br /> <input name="Submit" type="submit"
 class="CascadeButton" value="Send Cascade"  />

 <input type="reset" value="Clear Fields" class="ResetButton" />
 </form>

下面是我应用于 processTitle 文本字段的 Javascript。

function prepareEventHandlers() {
    document.getElementById("cascader").onsubmit = function() {
        // prevent a form from submitting if no email.
        if (document.getElementById("processTitle").value == "") {
            document.getElementById("errorMessage").innerHTML = "Please enter a value";
            // to STOP the form from submitting
            window.scrollTo(0, 0);
            document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
            // to turn the field background color
            return false;
        } else {
            // reset and allow the form to submit
            document.getElementById("errorMessage").innerHTML = "";
            return true;
        }
    };
}
// when the document loads
window.onload =  function() {
    prepareEventHandlers();
};
// Changes the field color onFocus
function checkFieldValue() {
    if (document.getElementById("processTitle").value != "") {
            document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
            document.getElementById("errorMessage").innerHTML = "";
        }
    else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
}

最佳答案

我添加了一个小功能来检查是否选择了其中一个单选按钮。请参阅 javascript 底部的 checkRequiredRadioButtons。目前我只是将其链接到您现有的验证失败代码。

function prepareEventHandlers() {
        document.getElementById("cascader").onsubmit = function() {
          // prevent a form from submitting if no email.
          if (document.getElementById("processTitle").value == "" || !checkRequiredRadioButtons('cascadeType')) {
            document.getElementById("errorMessage").innerHTML = "Please enter a value";
            // to STOP the form from submitting
            window.scrollTo(0, 0);
            document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
            // to turn the field background color
            return false;
          } else {
            // reset and allow the form to submit
            document.getElementById("errorMessage").innerHTML = "";
            return true;
          }
        };
      }
      // when the document loads
    window.onload = function() {
      prepareEventHandlers();
    };
     // Changes the field color onFocus
    function checkFieldValue() {
      if (document.getElementById("processTitle").value != "") {
        document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
        document.getElementById("errorMessage").innerHTML = "";
      } else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
    }

    function checkRequiredRadioButtons(buttonsName) {
      var buttonSet = document.getElementsByName(buttonsName);

      for(i = 0; i < buttonSet.length; i++){
          if(buttonSet[i].checked == true)
            return true;
      }
      return false;
    }
<form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader">
  <div class="TargetCenter">
    <p><strong><span class="asterisk">*</span>Target Center</strong> 
    </p>
    <label>
      <input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />All Countries</label>
    <label>
      <input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />France
    </label>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />Bolivia
    </label>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />North America</label>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />United Kingdom</label>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />Baltics
    </label>
    <label>
      <input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />Slovakia
    </label>

    <label>
      <input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />Sweden
    </label>

    <label>
      <input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />Switzerland
    </label>
    <br />
  </div>
  <!--end of Cascade Target-->
  <div class="CascadeCategory"> <strong>
 <span class="asterisk">*</span>Cascade Category: </strong> 
    <label>
      <input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />Process
    </label>
    <label>
      <input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />Training
    </label>
    <label>
      <input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2" />Knowledge</label>
    <br />
  </div>
  <!--end
  of Cascade Category-->
  <div class="ProcessTitle"><strong><span
  class="asterisk">*</span>Process Title:    <input name="textfld"
  type="text" id="processTitle" iname="processTitle"
  onkeypress="checkFieldValue()"  />  </strong><span id="errorMessage"></span>
  </div>
  <!--end of Process Title-->
  <div class="CascadeType"> <strong><span class="asterisk">*</span>Cascade
  Type:</strong> 
    <label>
      <input type="radio" name="cascadeType" value="Release" />Release</label>
    <label>
      <input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />Update
    </label>
    <label>
      <input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />Reminder
    </label>
    <br />
  </div>
  <!--end of Cascade Type-->
  <div class="QuickDescr"> <strong><span class="asterisk">*</span>Quick
 Description: </strong>
    <br />
    <br />
    <textarea name="textfld" cols="70%" rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
  </div>
  <!--end of Quick Description-->
  <div class="Details">
    <strong><span class="asterisk">*</span>Details: </strong>
    <br />
    <br/>
    <textarea name="details" cols="70%" rows="10" id="details"></textarea>
  </div>
  <!--end of Description-->
  <div class="DueDate"> <strong><span class="asterisk">*</span>Due
 Date:</strong> 
    <input type="text" class="Due" name="DueDate" placeholder="mm.dd.yyyy" /> <span class="DueDateFormat">(mm.dd.yyyy)</span>
  </div>
  <!--end of Due date-->
  <br />
  <br />
  <br />
  <input name="Submit" type="submit" class="CascadeButton" value="Send Cascade" />

  <input type="reset" value="Clear Fields" class="ResetButton" />
</form>

如果您尝试动态确定是否有文本框或单选按钮,则可以调用 Element.getAttribute('type') 并进行比较。如:

var allInputs = document.getElementsByTagName('input');
for(i = 0; i < allInputs.length; i++){
    if(allInputs[i].getAttribute('type') == 'radio'){
        //Do radio button handling
    } else if(allInputs[i].getAttribute('type') == 'text'){
        //Do textbox handling  
    }
}

但是,如果您这样做,您需要注意,对于单选按钮,您将迭代组中的所有单选按钮,无论是选中还是未选中。以及您的提交和重置按钮。

关于javascript - 将验证功能应用于所有文本字段和单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952494/

相关文章:

javascript - 如何在 JavaScript 中获取 URL 的 anchor 部分?

c - 有条件地输入数组

c - 为什么这个c程序会崩溃?

javascript - canvas drawImage 第一次不绘制图像

javascript - 带有额外日期的工作日 Javascript

javascript - knockout js valueupdate 'afterkeydown' 事件更改不起作用

PHP:数组 $_POST 循环问题

f# - Array.Parallel 的“MaxDegreeOfParallelism”?

成员函数中的 C++ 线程

javascript - JavaScript 中可以编写连续的嵌套函数吗?