Is it possible to use the onclientclick
property of a button to do a clientside check. If the check returns true
, then fire the onclick
event. If the clientside check returns false
, don't fire the onclick
event.
Is that possible?
UPDATE:
These 2 work:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
The next 2 do not work:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
It submits the form both times.
Why is that?
You want to add
return
inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.In the server page create the button:
//Contains the server code
//Contains the JS code for the page
Yes you can, In onclientClick function call use
preventDefault()
OR
Sure. If you use
return false
within yourOnClientClick
it will prevent any navigation from happening. So you're code would look like:I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.
However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.
Many attributes should need to be handled in a ViewState but in this case I think we are good;