I am working on a website using asp.Net, and it includes a page called from an iframe.
This page named Districting, has a javascript code in the aspx page.
I created a function, that is executed when “Done” button is clicked. This function tests if the conditions that the user made are true.
If yes, another page is loaded, if no, an alert appears, and nothing happens.
But actually, something is happening: the page is refreshing which is not what I want.
This is the button:
<button id="Button1" onclick="testing()">Done</button>
This is the function testing:
function testing() {
if (conditions are true)
//Go to another page
else{
alert("Wrong decision");
//Stay in the current page without refreshing it
}
}
So all I need is to prevent the page from refreshing when clicking on “Done” button.
Thanks in advance:)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Change your code to
function testing() {
if (conditions are true)
return true;
else{
alert("Wrong decision");
return false;
}
}
and your tag to
<button id="Button1" onclick="return testing()">Done</button>
Also, see How to confirm navigation for a link in a href tag?, as it’s very similar.
Method 2
A button is standard an submit button, so is the button in an form?
If that’s true, you can takkle that problem when you define the type of the button:
<button type="button" id="Button1" onclick="testing()">Done</button>
Method 3
Your javascript function that’s firing onclick needs to return false. The following should work:
<button id="Button1" onclick="testing(); return false;">Done</button>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0