Reputation: 2474
I am trying to prevent the page from reloading or submitting when the user clicks the Cancel option. I looked around stackoverflow and have the same syntax for the problem I'm having, but I tried something like this and it still submits and reload the page on cancel option. How do I prevent it from doing anything and leave the page as-is on cancel?
JavaScript code:
// create an input element
var frm = document.getElementById("result");
var submitBtn = document.createElement("input");
submitBtn.type = "submit";
submitBtn.value = "Confirm Purchase";
frm.appendChild(submitBtn);
submitBtn.addEventListener('click', function()
{
// confirm the data
var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
if(submitQ)
{
alert('Your query has been submitted! Have a great day! :)');
}
else document.getElementById("result").onsubmit = false; // prevent the page from refreshing on Cancel option
});
HTML Code:
<form id="result" onsubmit="true">
<!--Store User Selection Text Node Element Here-->
<!--<p>Your DSLR budget range selected was:</p>
<p>The DSLR brand you selected was:</p>
<p>The type of photography you selected was:</p>
<p>The type of lenses you selected was:</p>
<input type="submit" value="Confirm Purchase"/>
<input type="button" value="Reset All"/>-->
</form>
Upvotes: 1
Views: 1386
Reputation: 85518
Change your event handler to address the form onsubmit
event rather than the submit buttons click
event. And return false if the user cancels :
frm.onsubmit = function(){
// confirm the data
var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
if(submitQ)
{
alert('Your query has been submitted! Have a great day! :)');
} else {
// prevent the page from refreshing on Cancel option
return false;
}
};
see fiddle -> http://jsfiddle.net/LGd2f/
Upvotes: 1
Reputation: 6120
Maybe you should try attaching the event to form submit event instead of on a button click, and then just return false or return true.
Upvotes: 0