您的 HTML 格式不正确。你应该做:
<input type="text" name="dt[]">
然后循环如下:
$('input[name^=dt]').each(function() {
// code
alert( this.value ); // $(this).val()
});
你想要做的事情是不可能的id
属性,但可以使用name
属性。id
应该始终是唯一的.
除此之外
您可以使用通用的class
所有人的名字input
s 然后循环 then 像:
$('input.common_cls').each(function() {
// code
});
Note
"#^dt"
根本不是一个有效的选择器。正确的语法是
'input[name^=dt]'
OR
input[id^=dt]
.
您可以像下面这样实现验证
// this function will return true if no empty
// input exists, otherwise it will return false
function noEmptyExists() {
return $('input[name^=dt]').filter(function() {
return !$.trim( this.value );
}).length === 0;
}
$(document).on('click','#sub1',function() {
if( noEmptyExists() ) {
alert('Success');
} else {
alert('Failed');
}
});
工作样本 http://jsfiddle.net/zZD9a/2/
根据进度更新
this.val()
是错的。
将此行更改为:
$(this).val()
经过聊天讨论并解决克隆问题后
完整代码
$(document).ready(function() {
var count = 1;
alert('doc ready');
var row = $("table#MyTable tr:eq(1)");
$(document).on('click', '#sub1', function() {
if (noEmptyExists()) {
alert('Success');
} else {
alert('Failed');
}
});
$(document).on('click', '#add_row', function() {
row.clone(true).find("input").each(function() {
$(this).val('').attr('id', function(_, id) {
var newcnt = id + count;
return id + count;
});
}).end().appendTo("table");
});
});
function noEmptyExists() {
return $('input[name^=dt]').filter(function() {
return !$.trim(this.value);
}).length === 0;
}
工作样本 http://jsfiddle.net/BGy4M/11/