使用jQuery循环遍历表单中的所有文本框

Tom*_*Tom 11 javascript jquery

我有一个像电子表格一样的表格.

我想验证每个文本框中的文本,如果它不是数字,请更改文本框的背景并显示一条消息.

除了循环部分,我可以做任何事情.

我猜这是......每个声明?

gdo*_*ica 15

$('form input[type="text"]').each(function(){
        // Do your magic here
        if (this.value.match(/\D/)) // regular expression for numbers only.
            Error();
});
Run Code Online (Sandbox Code Playgroud)

如果您有表单ID:

$('#formId input[type="text"]').each(function(){
        // Do your magic here
});
Run Code Online (Sandbox Code Playgroud)


Bra*_*tie 5

// locate all ":input" elements within a generic <form>,
// then use .each() to loop through all results
$('form :input').each(function(){
  var $el = $(this); // element we're testing

  // attempt to cast the form's value to a number
  var n = parseFloat($el.val());

  // check if the conversion passed
  if (isNaN(n)){
    // $el does not have a number in it
  }
});
Run Code Online (Sandbox Code Playgroud)

我想你正在追求的是什么.您还可以指定input[type="text"]是否要更具体<input type="text" ... />

或者,更简洁:

$('form input[type="text"]').each(function(i,e){
    if (isNaN(parseFloat(e.value,10))){
        $(e).css('backgroundColor','red');
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @gdoron不只是`<select>`甚至是`buttons` (2认同)