我正在处理一个向表格添加动态表格行的表单,我已经为它做了一些验证,这对我来说很好,但现在我面临着一个新的挑战,我想验证一个文本框,它将动态添加到每一行,但问题是,我只想验证该文本框,当它之前的其他文本框不为空时,我被困在这里。我知道我可以对该id中的每个元素使用.each(),但我不知道如何绑定该验证中行中的每个文本框,因为当最后一个文本框(“我需要验证”)不为空时,行会自动相加,如果所有文本框都不为空,则不会给出任何错误。
下面是我的验证代码:
if($('[id^="invoice_"]').val() =="" || $('[id^="invoice_"]').val() ==null || $('[id^="invoice_"]').val() ==0){
alert("Invoice Number Cannot Be Empty");
$("#savetodb").attr("disabled", "disabled");
console.log("1");
return false;
}else{
console.log("2");
$("#savetodb").removeAttr("disabled"); 发布于 2013-10-24 17:47:20
你不需要为每个输入添加选择器...尝试使用循环
$.each($('[id^="invoice_"]'),function(i,v){
if(this.value=="" || this.value==null || this.value=="0"){
alert("Invoice Number Cannot Be Empty");
$("#savetodb").prop("disabled", true);
console.log("1");
return false;
}else{
console.log("2");
$("#savetodb").prop("disabled", false);
} 是的,这必须在您的提交函数中,并且应该在添加所有输入之后调用。如果您使用的是最新版本的jquery (即1.6+),建议使用prop()。
发布于 2013-10-24 19:04:38
试试这个:也许它会对你有所帮助。
代码端(.cs页面):
string str = "";
str = "<table>";
for (int i = 1; i <= 5; i++)
{
str = str + "<tr><Label id='lbl" + i.ToString() + "' runat='server'>Lable " + i.ToString() + "</Label>";
str = str + "<input type='Text' id='txt" + i.ToString() + "' onblur='checkValidation(this);'/></tr><br /><br />";
}
str = str + "</table>";
Response.Write(str);设计端(.aspx页面):
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function checkValidation(ctrl) {
var returnNow = false;
var i = 0;
$('input[type=text]').each(function (index) {
if (ctrl.id == this.id) {
if ($(this).val() == '' || $(this).val() == null) {
alert('enter some val for Label ' + (index + 1).toString());
}
return false;
}
else {
if ($(this).val() == '' || $(this).val() == null) {
alert('Enter some value for Label ' + (index + 1).toString());
return false;
}
else {
returnNow = true;
}
}
});
}
</script>https://stackoverflow.com/questions/19562371
复制相似问题