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 PointsHow can you pass the Id input of a form to variable then back to html id?
The value of totalExpenses flashes on the screen. How would you get the value to stay there just using JavaScript?
<body>
<form >
Rent: <input type="text" name="monthRent" id="monthRent">
Electric: <input type-"text" name="monthElectric" id="monthElectric">
Phone: <input type="text" name="monthPhone" id="monthPhone">
InterWebs: <input type="text" name="monthWeb" id="monthWeb">
<button onclick="myFunction()"> Try it</button>
<p id="outPut">
</p>
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;
}
1 Answer
Colin Marshall
32,861 PointsYou should handle the onclick in your JavaScript so that you can prevent the default action when the button is clicked. Add this to your javascript after myFunction():
document.getElementById("sum-button").onclick=function(e){
e.preventDefault();
myFunction();
}
Then change your html button to the following:
<button id="sum-button">Try it</button>
Kyle Myers
1,051 PointsKyle Myers
1,051 PointsThis still isn't working for me. Does that code go after function myFunction {
}
..code here?