我想在页面上做表单验证,但无论如何,每次都提交到后台执行,我想在f_doSave()返回false时,不执行doSave方法,请各位高手指点,谢谢!!页面:<script type="text/javascript" language="javascript">
function f_doSave()
{
var str = "";
str = document.all.txtUserName.value;
if(str.length > 0)
{
return true;
}
else
{
return false;
}
}
</script>
</head><table>
<tr>
<td> <asp:TextBox ID="txtUserName" runat="server" Width="100" /></td>
</tr>
<tr>
<td><asp:Button ID="btnSave" runat="server" Width="50" Text="保存" OnClick="doSave" /></td>
</tr>
</table>
后台:protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.btnSave.Attributes.Add("onclick", "return f_doSave();");
}
}
protected void doSave(object sender, EventArgs e)
{
string str = this.txtUserName.Text.Trim();
if (str.Length > 0)
{
Response.Write("<script>alert('" + str + "')</script>");
}
}
就这样,可以执行上面的JAVASCRIPT,但如论返回true or false,都能执行doSave方法。
function f_doSave()
{
var str = "";
str = document.all.txtUserName.value;
if(str.length > 0)
{
return true;
}
else
{
return false;
}
}
</script>
</head><table>
<tr>
<td> <asp:TextBox ID="txtUserName" runat="server" Width="100" /></td>
</tr>
<tr>
<td><asp:Button ID="btnSave" runat="server" Width="50" Text="保存" OnClick="doSave" /></td>
</tr>
</table>
后台:protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.btnSave.Attributes.Add("onclick", "return f_doSave();");
}
}
protected void doSave(object sender, EventArgs e)
{
string str = this.txtUserName.Text.Trim();
if (str.Length > 0)
{
Response.Write("<script>alert('" + str + "')</script>");
}
}
就这样,可以执行上面的JAVASCRIPT,但如论返回true or false,都能执行doSave方法。
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{ //这里改一下试试
//this.btnSave.Attributes.Add( "onclick ", "return f_doSave(); ");
this.btnSave.Attributes.Add( "onclick ", "javascript:return f_doSave(); ");
}
}
protected void doSave(object sender, EventArgs e)
{
string str = this.txtUserName.Text.Trim();
if (str.Length > 0)
{
Response.Write( " <script> alert( ' " + str + " ') </script> ");
}
}
而其他电脑可以执行。可能浏览器的不同而造成的。尝试onclick="if(dosave())return true; else return false;"看看可以不?
{
if(!IsPostBack)
{
this.btnSave.Attributes.Add( "onclick ", "if(false == f_doSave())return false; ");
}
}
<script type= "text/javascript " language= "javascript ">
function f_doSave()
{
var str = " ";
str = document.getElementById ( "txtUserName" ).value;
if(str.length > 0)
{
return true;
}
else
{
return false;
}
}
</script>