April 6, 201016 yr Hey everyone I have a javascript function that runs a mortgage calculator. However when the user clicks calculate the function works but the page refreshes. Does anyone know how I can stop this? I assume so kind of preventDefault thing. Here is the code for the calculate button. <ul class="sub"><li><label class="pad2"> </label></li><li><input class="submit" type="submit" value="Calculate" onClick="computeForm(document.form1)" /> <input class="submit" type="submit" value="Reset" onClick="resetForm()" /></li></ul> Also if you want to see the site where the problem is - http://www.aspire-dns.com/beta_layout/index.php If you click on "how much will my mortgage cost" on the right you will see the mortgage calculator. Thanks
April 6, 201016 yr Replace: computeForm(document.form1) with: computeForm(document.form1);return false Replace: resetForm() with: resetForm();return false Edited April 6, 201016 yr by andyl
April 6, 201016 yr preventDefault is the way to do it if you're trying to keep your JavaScript seperate from your mark up. The problem is that it only works in standards-based browsers, and it requires the event. The John Resig stopDefault function looks like this (and I'm pretty sure this is how jQuery's preventDefault works): function stopDefault(evt) { if (evt && evt.preventDefault) { evt.preventDefault(); } else { window.event.returnValue = false; } return false; } The event is passed to any standards-based browser as the first argument to function, and referenced from the window object in Internet Explorer. Looking at an article on How To Create, it seems that the easiest way to pass that to a function that requires other arguments is to write "arguments[0]", which simply refers to the first argument of the function. Essentially, you'd change your computeForm function to start function computeForm(evt, form) {... and you'd change your call to computeForm(arguments[0], document.form1) If you want to get more advanced, it's possible to use events to identify the element that triggered the event (in this case, the submit button) and run up the DOM tree until you find the parent form meaning that you won't have to add any arguments with you call your code. Edit: Just thought, to actually stop the default action you'll need to call stopDefault. Essentially, put this line at the bottom of your computeForm function: stopDefault(evt);
Create an account or sign in to comment