alisia123
alisia123

Reputation: 365

How to force function execution after input with JavaScript

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.

Upvotes: 2

Views: 3538

Answers (3)

James-Jesse Drinkard
James-Jesse Drinkard

Reputation: 15703

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.

Upvotes: 0

robbymurphy
robbymurphy

Reputation: 741

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
    }
}

Upvotes: 3

m.edmondson
m.edmondson

Reputation: 30882

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.

Upvotes: 0

Related Questions