0

I have created a function that when the use fills in the two inputs comm and hour it populated the result in another input called phone.

calculate = function()
{
    var comm = document.getElementById('comm').value;
    var hour = document.getElementById('hour').value; 
    document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}

At the moment if you type in comm and hour and then you click outside the input it calculates the result in phone.

What I am trying to achieve is to calculate at the moment you type on any of the two fields.

I have tried to find something that can help me here, but with no luck. Any advice?

5 Answers 5

3

Look into onkeydown. Something like the following code.

document.onkeydown = calculate = function()
{
    var comm = parseFloat(document.getElementById('comm').value);
    var hour = parseFloat(document.getElementById('hour').value); 
    document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}

This will call that function whenever a key is pressed on the page.

Sign up to request clarification or add additional context in comments.

3 Comments

@lStoilov Awesome! Consider accepting if you feel like it helped you so others can benefit also. Happy coding!!
Will accept in 10 min, due to some limitation of the website :)
@ISoilov Thanks! Happy coding!!
2

As @CharlieFish answer Use document.onkeydown to call event on key down and use parseFloat to convert your values to float

document.onkeydown = calculate = function()
{
    //hope you have define phone value
    var comm = parseFloat(document.getElementById('comm').value);
    var hour = parseFloat(document.getElementById('hour').value); 
    document.getElementById('phone').value = Math.round(comm*hour*phone/60);
}

Comments

1
document.body.onkeypress(function(){
   // invoke your function here calculator()
   // additional logic can we added here too.
})

Comments

1

If you want it to start working immediately use a IIFE (immediately invoked function expression) and add an event listener for 'keyup' so it will fire once the value in the input field has been set:

(function(){
  document.getElementById('foo').addEventListener('keyup',function(){
  //add your logic here
  console.log('someone pressed a key!');
});
}());

...just remember to parseFloat the values in your example before you try to calculate, as when you get them from the element they will be typeof string ...

so value = parseFloat(value);

Comments

0

I think what you need is trigger calculate function at text change event, just try this

<input type="text" id="comm" onchange="calculate();"/>
<input type="text" id="hour" onchange="calculate();"/>

Comments

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.