Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kyle Myers
1,051 PointsPrevent form redirect OR refresh on submit?
I want my page not to refresh when clicking the Submit button on a form or how would I display totalExpenses on that page with out it going away?. If you ran my code you can see it sends totalExpenses to the id "outPut" but goes away after the page is refreshed.
function myFunction() {
var monthRent = document.getElementById("monthRent").value;
var monthElectric = document.getElementById("monthElectric").value;
var monthPhone = document.getElementById("monthPhone").value;
var monthWeb = document.getElementById("monthWeb").value;
var totalExpenses = parseInt(monthRent) + parseInt(monthElectric) + parseInt(monthPhone) + parseInt(monthWeb);
document.getElementById("outPut").innerHTML = totalExpenses;
alert(totalExpenses);
}
1 Answer
Grace Kelly
33,990 PointsHi Kyle, I would try the preventDefault() function to prevent the browser from refreshing the page, here's an example using jQuery:
//when the form is submitted
$('form').submit(function (evt) {
evt.preventDefault(); //prevents the default action
}
You can read more about preventDefault() here