ashwnacharya
ashwnacharya

Reputation: 14871

How to avoid a postback in JavaScript?

I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this?

Upvotes: 9

Views: 18618

Answers (4)

Joe Lencioni
Joe Lencioni

Reputation: 10511

Is this what you are trying to do?

<input type="button" id="myButton" value="Click!" />

<script type="text/javascript">
document.getElementById('myButton').onclick = function() {
    var agree = confirm('Are you sure?');
    if (!agree) return false;
};
</script>

Upvotes: 2

Chris Cudmore
Chris Cudmore

Reputation: 30151

function HandleClick()
{
 // do some work;

if (some condition) return true; //proceed
else return false; //cancel;
}

set the OnClientClick attribute to "return HandleClick()"

Upvotes: 0

Tom
Tom

Reputation: 22841

Basically what Wayne said, but you just need to put 'return false;' in the function that presents the modal. If it's the value you want, let the postback happen. If not, have the function return false and it will stop the submit.

Upvotes: -1

Wayne
Wayne

Reputation: 39898

Adding "return false;" to the onclick attribute of the button will prevent the automatic postback.

Upvotes: 17

Related Questions