使用jQuery循环遍历表单中的所有文本框
我有一个像电子表格一样的表格。
我想validation每个文本框中的文本,如果它不是数字,请更改文本框的背景并显示消息。
除了循环部分,我可以做任何事情。
我猜这是……每个声明?
$('form input[type="text"]').each(function(){ // Do your magic here if (this.value.match(/\D/)) // regular expression for numbers only. Error(); });
如果您有表单ID:
$('#formId input[type="text"]').each(function(){ // Do your magic here });
// locate all ":input" elements within a generic
我想你正在追求的是什么。 如果你想更具体地对你也可以指定
input[type="text"]
或者, 更简洁 :
$('form input[type="text"]').each(function(i,e){ if (isNaN(parseFloat(e.value,10))){ $(e).css('backgroundColor','red'); } });
jsFiddle( http://jsfiddle.net/BctQP/18/ )
对于每个循环:
for (var $input in $('input[type="text"]')) { //code here }
这对我有用! :)参考
使用jQuery和https://stackoverflow.com/a/311589 遍历表单中的所有文本框
$(document).ready(function() { $('form button[type=submit]').click(function() { // attach the listener to your button debugger; var sub_form = $(this.form); // use the native JS object with "this" $(':input[class="required"]', sub_form).each(function() { if (this.value == "") { alert("is empty"); } else { alert(this.value); } }); }); });
body { margin: 5px; padding: 5px; border: 1px solid black; } #topContainer { width: auto; margin: 2px; padding: 2px; border: 1px solid black; height: 100px; } #mainContainer { width: auto; height: 200px; margin: 2px; padding: 2px; border: 1px solid black; } #footerContainer { width: auto; height: 200px; margin: 2px; padding: 2px; border: 1px solid black; } .gridRow4 { margin: 2px 5px; width: 25%; } .gridRow5 { margin: 2px 5px; width: ; }
text goes here