【问题标题】:Loop through select from fields and validate循环从字段中选择并验证
【发布时间】:2019-02-06 21:06:55
【问题描述】:

我正在尝试遍历多个文本并选择表单中的框并验证它们已被回答。

我已使用以下代码循环遍历文本框,但可以弄清楚如何在选择框上执行类似操作。

<form name="Form1"></form>
    <label>Question 1</lable>
    <input type="text" class="required" name="question1">

    <label>Question 2</lable>
    <select class="required" name="question3">
        <option value="0">a</option>
        <option value="1">b</option>
        <option value="2">c</option>
        <option value="3">d</option>   
    </select>
    <button role="button"id="Go">Go</button>';
</form>


<script>
(function (){
    $('#Go').on('click', function(e){
        e.preventDefault();
        genericValidationText('form[name="Form1"]');
        genericValidationSelect('form[name="Form1"]');
    });
}());

function genericValidationText (formName) {
    document.forms.noValidate = true;
    var notValid;

    // PERFORM GENERIC CHECKS
    // INPUT form fields
    $(formName + ' *').filter(':input').each(function(){
        var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
        performValidation(formElement);
    });

    function performValidation(formElement){
        if ($(formElement).hasClass('required')) {

            notValid = false;
            if (!($.trim($(formElement).val()))){
                notValid = true;
            };

            if (notValid === true) {
                showErrorMessage(formElement);
            };
        };
    }
}


function genericValidationSelect (formName) {
?????
}
</script>

【问题讨论】:

  • 你想在选择中验证什么?

标签: javascript jquery forms validation drop-down-menu


【解决方案1】:

您可以通过检查选择元素的.val() 的结果,以与&lt;input /&gt; 元素大致相同的方式验证&lt;select&gt; 元素。

要记住的是,&lt;select&gt; 默认有一个值(对应于用户最初在浏览器中可见的&lt;option&gt;)。这实际上会导致对&lt;select&gt; 的验证通过(即使用户没有明确选择选择选项)。

要解决此问题,请考虑将默认 &lt;option&gt; 添加到 &lt;select&gt;,如下所示:

 <option selected disabled>Please select something</option>

添加此选项意味着&lt;select&gt; 上的验证将失败,直到用户通过选择有效选项实际与&lt;select&gt; 互动(之后,选择上的验证将通过):

(function() {
  /* Consider using submit on form, rather than a click event 
  listener on the Go button */
  $('form[name="Form1"]').submit(function(e) {
    e.preventDefault();
    /* Exclude call to genericValidationText() for
    this snippet to simplify it
    genericValidationText('form[name="Form1"]');
     */
    genericValidationSelect('form[name="Form1"]');
  });
}());

function genericValidationSelect(formName) {
  
  let notValid = false;
  
  /* Iterate each select in the form */
  $('select', formName).each(function() {
    
    /* Check value in similar way. If null value, 
    then consider the select invalid */
    var selectedOption = $(this).val();
    if (selectedOption === null) {
      notValid = true;
    }
  });

  if(notValid) {    
      alert('Please select an option');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
  <!-- Fixed : typo -->
  <label>Question 1</label>
  <input type="text" class="required" name="question1">
  <label>Question 2</lable>
    <select class="required" name="question3">
        <!-- Added default "no value option" to demonstrate validation -->
        <option selected disabled>Please select something</option>
        <option value="0">a</option>
        <option value="1">b</option>
        <option value="2">c</option>
        <option value="3">d</option>   
    </select>
    <button role="button"id="Go">Go</button>
</form>

希望这会有所帮助!

【讨论】:

  • 感谢您的解决方案完美运行。中继有用且清晰。
  • 太棒了!很高兴我能帮忙?
【解决方案2】:

以下应该有效:

const changeEventHandler = e => {
    const value = e.target.options[e.target.selectedIndex].value;
    console.log(value); //Validate value...
}

const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多