简体   繁体   English

jQuery从$(“ input”)数组获取输入val()

[英]jQuery get input val() from $(“input”) array

I have a function that returns whether or not every text input in a form has a value. 我有一个函数,该函数返回表单中每个文本输入是否都具有值。

When I first made the function it looked like this: 当我第一次创建函数时,它看起来像这样:

function checkInput(inputId) {
check = 0;          //should be 0 if all inputs are filled out
for (var i=0; i < arguments.length; i++) {   // get all of the arguments (input ids) to check
    var iVal = $("#"+arguments[i]).val();

  if(iVal !== '' && iVal !== null) {
    $("#"+arguments[i]).removeClass('input-error');
  }
  else {
    $("#"+arguments[i]).addClass('input-error');
    $("#"+arguments[i]).focus(function(){
      $("input").removeClass('input-error');
      $("#"+arguments[i]).off('focus');
    });
  check++;
  }

}

  if(check > 0) {
    return false; // at least one input doesn't have a value
  }
  else {
    return true; // all inputs have values
  }

}

This worked fine, but when I called the function I would have to include (as an arstrong textgument) the id of every input I wanted to be checked: checkInput('input1','input2','input3') . 这很好用,但是当我调用该函数时,我必须包括(要作为Arstrong文本)要检查的每个输入的ID: checkInput('input1','input2','input3')


Now I am trying to have my function check every input on the page without having to include every input id. 现在,我试图让函数检查页面上的每个输入,而不必包含每个输入ID。

This is what I have so far: 这是我到目前为止的内容:

 function checkInput() { var inputs = $("input"); check = 0; for (var i=0; i < inputs.size(); i++) { var iVal = inputs[i].val(); if(iVal !== '' && iVal !== null) { inputs[i].removeClass('input-error'); } else { inputs[i].addClass('input-error'); inputs[i].focus(function(){ $("input").removeClass('input-error'); inputs[i].off('focus'); }); check++; } } if(check > 0) { return false; } else { return true; } } 

When I call the function it returns this error: 当我调用该函数时,它将返回此错误:

Uncaught TypeError: inputs[i].val is not a function 未捕获的TypeError:inputs [i] .val不是函数

What am I doing wrong? 我究竟做错了什么?

When you do inputs[i], this returns an html element, so it is no longer a jquery object. 当您输入input [i]时,它将返回一个html元素,因此它不再是jquery对象。 This is why it no longer has that function. 这就是为什么它不再具有该功能的原因。

Try wrapping it with $() like $(inputs[i]) to get the jquery object, and then call .val() like: 尝试用$()像$(inputs [i])一样包装它以获得jquery对象,然后像下面那样调用.val():

 $(inputs[i]).val()

If you are going to use this in your for loop, just set it as a variable: 如果要在for循环中使用它,只需将其设置为变量即可:

var $my_input = $(inputs[i])

Then continue to use it within the loop with your other methods: 然后继续在循环中与其他方法一起使用它:

$my_input.val()
$my_input.addClass()

etc.. 等等..

if you use jquery .each() function, you can do it a little cleaner: 如果您使用jquery .each()函数,则可以使其更加.each()

 $(document).ready(function() { $('.submit').on('click', function() { $('input').each(function() { console.log('what up'); if($(this).val().length < 1 ) { $(this).addClass('input-error'); } else { $(this).removeClass('input-error'); } }); }); }); 
 .input-error { background-color: pink; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <input type="text" /><br/> <br/> <a href="#" class="submit">SUBMIT</a> 

This is actually a very simple fix. 这实际上是一个非常简单的修复。 You need to wrap you jquery objects within the jquery constructor $() 您需要在jquery构造函数$()包装jquery对象

Such as for inputs[i].val() to $(inputs[i]).val(); 例如对于inputs[i].val()$(inputs[i]).val();

Here is the full working example: 这是完整的工作示例:

http://jsbin.com/sipotenamo/1/edit?html,js,output http://jsbin.com/sipotenamo/1/edit?html,js,output

Hope that helps! 希望有帮助!

This is exactly one of the things the .eq() method is for. 这正是.eq()方法的目的之一。 Rather than using inputs[i] , use the following: 而不是使用inputs[i] ,而是使用以下内容:

// Reduce the set of matched elements to the one at the specified index.
inputs.eq(i)

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. 给定一个表示一组DOM元素的jQuery对象, .eq()方法从该元素集中的一个元素构造一个新的jQuery对象。 The supplied index identifies the position of this element in the set. 提供的索引标识此元素在集合中的位置。

in this case, I would make use of the jQuery.each() function for looping through the form elements. 在这种情况下,我将使用jQuery.each()函数来循环访问表单元素。 This will be the modified code 这将是修改后的代码

function checkInput() {
        var $inputs = $("input"),
            check = 0;
        $inputs.each(function () {
            val = $.trim($(this).val());
            if (val) {
                $(this).removeClass('input-error');
            }
            else {
                $(this).addClass('input-error');
                $(this).focus(function () {
                    $("input").removeClass('input-error');
                    $(this).off('focus');
                });
                check++;
            }
        });
        return check == 0;
    }

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

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