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
Matthew Rigdon
8,223 PointsTaking an input and modifying with math? (HTML question?)
I'm looking to have an input field on a website where a user can type in a value. Once submitted (using a button), I want to perform math on the user's input. Example: person inputs '8' into a field, and my program divides that number by 2 and outputs '4,' waits a second and divides the new value by 2 again, outputs '2,' etc.
I figured I would use JavaScript/jQuery to do the math portion and output an answer, however, I was unsure of what I should do to make the visual appearance of input. I was looking into HTML's forms? Would that make sense? Or is there a better method?
2 Answers
Jeff Lemay
14,268 PointsHere's a rough example:
<input type="text" id="response" />
<input type="submit" id="calculate" />
<p id="answer"></p>
$('#calculate').on('click', function(e){
e.preventDefault();
var value = $('response').val();
value = value / 2 / 2;
$('answer').text(value);
});
You could (and probably should) do this without using a submit button and calculate whenever the user enters in a value:
$('#response').keyup(function(){
var value = $('this').val();
value = value / 2 / 2;
$('answer').text(value);
});
Matthew Rigdon
8,223 PointsThis is very helpful! Do you know anyway to have this function continually repeat every second and keep re-posting the new answer?
Jeff Lemay
14,268 PointsThe 'keyup' function should update every time you change the number in the text input. Or do you want the answer to be divided by 2 after every second? I don't have a great answer off the top of my head.
Ted Sumner
Courses Plus Student 17,967 PointsI don't know the answer but I would search mdn JavaScript delay.
Jacob Mishkin
23,118 PointsJacob Mishkin
23,118 Pointsfor the visual appearance just use CSS. That's what its there for.