简体   繁体   English

遍历输入字段时设置标志

[英]Set flag when looping through input fields

I have a series of multiple text fields and a text area. 我有一系列的多个文本字段和一个文本区域。 I'm looping through the text fields and the text area and checking if there is a value. 我正在遍历文本字段和文本区域,并检查是否有值。 If there is not a value I set a flag that says pass=false. 如果没有值,则设置一个标志,指示pass = false。 Otherwise I set pass=true and would like to fire a custom event if everything evaluates to true. 否则,我将设置为pass = true,并在所有结果都为true时触发自定义事件。 The problem is that because one input field evaluates to true it evaluates them all to true even though two of the fields have no value in them. 问题在于,因为一个输入字段的评估结果为true,所以即使其中两个字段中没有值,它也会将其全部评估为true。 How would I go about doing this if I wanted it so that all fields have to be filled in but still set pass=false if one or two of them are filled in? 如果需要,我将如何去做,以便必须填写所有字段,但如果其中一个或两个字段被填写,仍然设置pass = false Any help is greatly appreciated! 任何帮助是极大的赞赏!

JS Fiddle link: http://jsfiddle.net/YyAjp/12/ JS小提琴链接: http : //jsfiddle.net/YyAjp/12/

HTML: HTML:

<form name="headerForm">
  <label for="fname">*First Name</label>
  <input type="text" class="text" id="fname" name="fname" />
  <br/>   

  <label for="mname">*Middle Name</label>
  <input type="text" class="text" id="mname" name="mname" />
  <br/>     

  <label for="fname">*Last Name</label>
  <input type="text" class="text" id="lname" name="lname" />
  <br/>    

  <label for="notes">*Notes</label>
  <textarea name="notes" /></textarea>

  <a href="#" id="submit">Submit</a>
</form>   

JQUERY JQUERY

$(document).ready(function() {       
$("#submit").on('click', function() {    
    var pass;
    $("input,textarea,select").each(function() {
        if($(this).val() === ''){
            pass = false;
            $(this).prev('label').css('color','red');
        } else { 
            pass = true;
            $(this).prev('label').css('color','black');
        }
    });
    console.log(pass);
    if(pass){ alert('trigger custom event') } else { alert('pass failed'); }
});                    
});

Change 更改

pass = true;

into

pass = pass && true;

and initialize it to true : 并将其初始化为true

$("#submit").on('click', function() {    
    var pass = true;

http://jsfiddle.net/mblase75/pgM5X/ http://jsfiddle.net/mblase75/pgM5X/

(You might also want to use $.trim() on the values first.) (您可能还想先在这些值上使用$.trim() 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM