I have some legacy codes, some implemented in JavaScript and some implemented in C#. Now I have to write a piece of code to decide whether or not to fire OnClick depends on some conditions. I want to implement it by checking the condition in the OnClientClick. I tried some methods from the Internet, but they did not work. (I'm new to JavaScript and C#, so I'm not really understand the solutions, for example, setting OnClientClick="return confirm ('This will delete the report. Continue?'); return false; ", doesn't it always return before executing "return false"?")
my codes are as follow
aspx file:
<div id="searchBtn"><asp:LinkButton ID="SearchButton" OnClientClick="return SetInputString(); return false;" OnClick="SearchClick" ValidationGroup="search" runat="server"><img src="images/btn_search.jpg" alt="検索" /></asp:LinkButton></div>
js file:
function SetInputString() {
var textbox = document.getElementById("textForm");
var inputString = document.getElementById("inputString");
clearNonInteractiveTimer();
inputString.value = textbox.value;
if (/^[0-9]{6}$/.test(inputString.value)) {
EvaluateEnteredSearch(inputString.value);
return false;
} else {
return true;
}
}
cs file:
public void SearchClick(object sender, EventArgs e){
...
}
CodePudding user response:
Confirm
is a method "built-in" into the Javascript.
This method is modal: it stops the execution of scripts and prevents the user from interacting with the rest of the page until the window is closed.
So no, the output will depend on the user's choice.
return false
means that you are canceling the default action of the pressed button.
There are two ways to tell the browser that you want to cancel the default action for some event, in this case, cancel the following link: call event.preventDefault ()
or return false
from the handler function. The second only works if you assign a handler using the onevent
attribute like so:
<a href="//google.com" onclick="return false"> google </a>
Or like this:
<a href="//google.com"> google </a>
<script>
document.getElementsByTagName ('a') [0] .onclick = function () {
return false;
}
</script>
More info here: How to undo a default action
Now, what about ur code.
OnClick
Event sends a request to the server and performs an action in response.
OnClientClick
is very similar to the onclick function we use to write in Javascript ... that is, it executes statements on the client side without sending them to the server.
SetInputString
will be called first, if true
- SearchClick
will be called
Also, more info here: when to call the Server onClick vs OnClientClick