我如何在javascript的gridview内的按钮单击上应用文本框空白验证?
一个网格视图,每行包含2个文本框和一个保存按钮.我想在单击相应的保存按钮时验证文本框.
我已经应用了逻辑,但问题是它仅适用于经过硬编码的textBox id.如何修改此代码,使其适用于所有gridview行?
function gvValidate() {
var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
if(grid!=null)
{
var Inputs = grid.getElementsByTagName("input");
for(i = 0; i < Inputs.length; i++)
{
if(Inputs[i].type == 'text' )
{
if (Inputs[i].id == 'ctl00_contentPlaceHolderSubScreen_GridViewCTInformation_ctl02_TextBoxCTTermCode')
{
if (Inputs[i].value == "") {
alert("Enter values,blank is not allowed");
return false;
}
}
else if (Inputs[i].id == 'ctl00_contentPlaceHolderSubScreen_GridViewCTInformation_ctl02_TextBoxCTTermDesc') {
if (Inputs[i].value == "") {
alert("Enter values,blank is not allowed");
return false;
}
}
}
}
return true;
}
}
Protected Sub GridViewTaxInformation_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewTaxInformation.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim btnSave As Button = DirectCast(e.Row.FindControl("ButtonSave"), Button)
btnSave.Attributes.Add("onclick", "return gvValidate()")
End If
Catch ex As Exception
Common.WriteLog(ex.Message)
Common.WriteLog((ex.StackTrace))
Response.Redirect("..\Errors.aspx", False)
End Try
End Sub
解决方法:
终于我解决了我的问题.我刚刚将gridview的行索引传递给了javascript函数.
这是代码
function gvValidate(rowIndex) {
var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
if(grid!=null) {
var Inputs = grid.rows[rowIndex + 1].getElementsByTagName("input");
for(i = 0; i < Inputs.length; i++)
{
if(Inputs[i].type == 'text' )
{
if (Inputs[i].value == "") {
alert("Enter values,blank is not allowed");
return false;
}
}
}
return true;
}
}
Protected Sub GridViewCTInformation_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewCTInformation.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim btnSave As Button = DirectCast(e.Row.FindControl("ButtonCTInfoSave"), Button)
btnSave.Attributes.Add("onclick", "return gvValidate(" + e.Row.RowIndex.ToString() + ")")
End If
Catch ex As Exception
Common.WriteLog(ex.Message)
Common.WriteLog((ex.StackTrace))
Response.Redirect("..\Errors.aspx", False)
End Try
End Sub