Do some math in one input upon entry of a number in another?

Hi there everyone!

I’m wondering if it’s possible to insert a result of some math into an input based on a number being entered in another. To explain what I’d like:

<input type="text" name="1">
<input type="text" name="2">

Where 2 would automatically update to reflect (text1’svalue + 30%) but only if I click something outside of text entry 1. I may not always want to use this function, so I would like it available if I click a button and not automatically upon entry of 1.

Is this possible?

Thanks for your time!

Why would you change the name of an element? Or did you mean value?

I did mean value and I’ve edited the post to take into account that I wouldn’t always want to use this function. Sometimes I would be entering a value not equal to the equation into #2 on my own.

I’ve found a fantastic javascript snippet while googling and the math portion is operating as it should but I’m having problems moving it to my page:

Here’s the js all by it’s lonesome:
And here it is implemented into it’s new home:

Basically, “price” should update when “ciw[1][price]” gets a number. Right now, nothing is happening. I have the function in the head, I’ve called jquery prior to the function and I’ve kept the names correct in the function. What have I done incorrectly to break it?

I’ve figured out what I did wrong and I’ve got the math updating price when ciw[1][price] is updated. The issue I’m having now is that I’d like to to happen based on pressing a button beside ciw[1][price]. Is that something that’s possible or am I restricted to the function occurring upon update of the text box?

Thanks for your time!

A button like this?

<button id="updatePrice">Press me!</button>

With a click event attached to it?

$("#updatePrice").on('click', updatePrice);

Hi there Paul and thanks for the help!

It does update the price but it also submits the form it’s inside of. Is there a way to prevent that from happening and have it only update the price?

Yes, just tell the form that it’s a button.

<button id="updatePrice" type="button">Press me!</button>

or move the button tag outside the form tag where its type defaults to button instead of submit.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.