2

I am making a small calculator (just for JavaScript learning) and I have two input fields for fraction calculation:

  1. Field: numerator
  2. Field: denominator

And a button "Calculate fraction" which executes the function myFraction(numerator,denominator) when user clicks on it.

Is it possible to do the same without the Button? I mean JavaScript should recognize that someone is making input and then calculate the fraction automatically.

Tiago Sippert
  • 1,324
  • 7
  • 24
  • 33
alisia123
  • 365
  • 1
  • 8
  • 16

3 Answers3

3

You can hook into the onkeyup or onkeydown event handlers and call your function:

<input type="text" id="numerator" onkeyup="myFraction()" />
<input type="text" id="denominator" onkeyup="myFraction()" />

You'll need to grab the values of the text boxes inside the myFraction() function and check to see if they're blank before you output the fraction value to the screen though.

function myFraction() {
    if(document.getElementById("numerator").value != "" &&
       document.getElementById("denominator").value != "") {
        ...do calculations
    }
}
robbymurphy
  • 741
  • 2
  • 5
  • 16
0

Sure, I think you need onChange() (as the text is being edited) or onBlur() (when the textbox looses focus). See the difference here.

Since you're studying, jQuery can help with some of the nuances - including here.

Community
  • 1
  • 1
m.edmondson
  • 30,382
  • 27
  • 123
  • 206
0

Javascript is event driven, so yes, you can catch the event after they are typing with keyup or when the user moves off from a textbox control.

You could check the length of a textbox after they leave it, validate what they entered and then run the calculation.

I usually use blur to catch after a user leaves a textbox. I usually use Onchange for select.

James Drinkard
  • 15,342
  • 16
  • 114
  • 137
  • 1
    Onchange will also fire on input boxes, after blur *and* if the text has been changed. – Marcel Korpel Jun 16 '12 at 14:02
  • Thanks, but is it possible to do the calculation during the user is typing the numbers? – alisia123 Jun 16 '12 at 14:04
  • You have the keyup/keydown events that fire continuously, but you would have to be checking constantly to see if they were finished with their input and what mechanism would you use? Another function to check for length? You are making it too complicated I think. It would be a lot easier if you could show us some code. – James Drinkard Jun 16 '12 at 14:08