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.

1
  • have you tried sth like jQuery blur() method? Commented Jun 16, 2012 at 13:56

3 Answers 3

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

3 Comments

Onchange will also fire on input boxes, after blur and if the text has been changed.
Thanks, but is it possible to do the calculation during the user is typing the numbers?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.