我正在处理一个向表添加动态表行的表单我已经对它进行了一些验证,这对我来说很好,但是现在我正面临一个新的挑战,我要验证一个文本框,它将被添加动态地在每一行,但问题是我只想在其前面的其他文本框不为空时验证该文本框
我被困在这里我知道我可以对进入该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");
答案 0 :(得分:1)
你不需要为每个输入添加选择器...尝试使用循环
$.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()
答案 1 :(得分:0)
试试这个: 可能会对你有帮助......
代码方(.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>