JQuery:如何使用Each方法检查所有表单输入元素中的值

JQuery: How to use the Each method to check values in all form input element

本文关键字:输入 表单 元素 何使用 Each 检查 方法 JQuery      更新时间:2023-09-26
JQuery:新增功能

好吧,我很困惑,已经尝试了所有的变体,包括我在书和JQuery API中读到的内容。

我有以下样本标记

<form id="myForm" name="myForm" action="" method="post">
    <label>*Enter Input A:
        <br />
        <input type="text" id="inputA" name="inputA" />
    </label>
    <label>*Enter Input B:
        <br />
        <input type="text" id="inputB" name="inputB" />
    </label>
    <label>*Enter Input C:
        <br />
        <input type="text" id="inputC" name="inputC" />
    </label>
    <label>*Enter Input D:
        <br />
        <input type="text" id="inputD" name="inputD" />
    </label>
</form>
<p class="myText">Sample Text</p>

当页面通过fields/textboxes加载和I选项卡时,段落颜色会发生变化。这就是我想要的:blur function

我不明白的是:

除非我在最后一个textbox输入D中键入值,否则段落不会更改。为什么?如果任何一个框中有值,我需要更改该段。这个值只有一个吗?($(element).val() == '')

这是JQ:

 $('#myForm :input[type="text"]').blur(function () {
     $('#myForm input[type="text"]').each(function (i, element) {
         if ($(element).val() == '') {
             $(".myText").css("color", "#F00")
         } else {
             $(".myText").css("color", "#9A9A9A")
         }
     });
 });

小提琴在这里:JSfiddle示例

感谢您的解释

一旦满足所需条件,就不会脱离循环。相反,您将循环浏览所有文本框,最终如果最后一个文本框没有任何值,它将被设置为红色,无论前面的哪个文本框有值,因为这是迭代中的最后一个。相反,您可以使用return false; 突破.each()循环

 $('#myForm :input[type="text"]').blur(function () {
     $('#myForm input[type="text"]').each(function () {
         if (this.value == '') {
             $(".myText").css("color", "#F00")
         } else {
             $(".myText").css("color", "#9A9A9A");
                 return false;
         }
     });
 });

就这一点而言,你可以将其简化为:

 $('#myForm :input[type="text"]').blur(function () {
     $('.myText').css('color', function () { //use the css function callback
         return $('#myForm input[type="text"]').filter(function () { //Use filter to return the textboxes which has value
             return this.value != ''
         }).length == 0 ? "#F00" : "#9A9A9A"; // set the color accordingly
     });
 });

Fiddle

我更新了你的代码,请检查fiddle

http://jsfiddle.net/Wmrh6/11/

当你跳出循环时,你应该改变段落的颜色:

   if(changed)$(".myText").css("color", "#9A9A9A");else
          $(".myText").css("color", "#F00");