在 ASP.NET 代码中通过 javascript 发出警报后停止回发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18438002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop postback after alert by javascript in ASP.NET Code
提问by user2126933
I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
我有一个文本框和一个按钮,在按钮的 clientClick 上我调用了 javascript 函数,并且还有服务器端编码。
Problem is, the page gets post back even if I have return False in the javascript.
问题是,即使我在 javascript 中返回了 False,页面也会被回发。
Here is my javascript function:
这是我的 javascript 函数:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
我在我的表单上调用这个函数为:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />
回答by Harish Bhatt
Try to call JavaScript function as below:
尝试调用 JavaScript 函数如下:
OnClientClick="if(!validateform()){return false;}
where validateform()
should be your java script function. Your java script function should have return = true;
at the end of function in successfull execution, like in below function:
validateform()
你的java脚本函数应该在哪里。您的java脚本函数应该 return = true;
在成功执行的函数末尾,如下面的函数:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
请尝试让我知道它是否适合您。
Thanks, Harish
谢谢,哈里斯