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

HTML

Taking 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?

for the visual appearance just use CSS. That's what its there for.

2 Answers

Here'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);
});

Jeff Lemay

This is very helpful! Do you know anyway to have this function continually repeat every second and keep re-posting the new answer?

The '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.

I don't know the answer but I would search mdn JavaScript delay.