0

I would like to change the value of input fields in a form based on the input of one of the fields live without refresh before submitting the form.

For example

<input type="text" name="chance" value="50">

Let's say a user inputs 80 into the field.

Would I then be able to do the calculation 1/input x 98 where the input = 80 (so it would be 1/80 x 98).

I would then set this as the value of input of another field in the form.

<input type="text" name="payout" value="1/input x 98">

Without refreshing the page. TIA

Semger
  • 253
  • 1
  • 4
  • 12

1 Answers1

1

On change of chance you can set the value of payout like this.

<input type="text" name="chance" value="50"
onchange="document.getElementById('payout').value='1/'+this.value+'x 98'">

If you want on that on the go without need of enter then use

<input type="text" name="chance" value="50"
    onkeyup="document.getElementById('payout').value='1/'+this.value+'x 98'">

Chance: <input type="text" name="chance" value=""
   onkeyup="document.querySelector('input[name=payout]').value=this.value?1/this.value*98:''">

<br/><br/>Payout: <input type="text" name="payout" value=""><br/>

If you want to restrict the chance field to enter only number then check out this link

Community
  • 1
  • 1
vinayakj
  • 5,591
  • 3
  • 28
  • 48
  • The problem with this is that it still requires you to press enter to update the entry of the other fields. In there another augment unlike `onchange` which will be triggered when a value is entered but enter is not pressed. – Semger Jun 23 '15 at 11:50
  • didnt understand the other values(payout) should only change when there is change in chance right? or do you want it on keyup? – vinayakj Jun 23 '15 at 15:53
  • Whenever someone starts to enter something in the field chance, this number should also change live in payout. Cheers – Semger Jun 23 '15 at 15:56
  • Ok.. updated the answer with both use cases. check it out. – vinayakj Jun 23 '15 at 16:05
  • I'm not sure why, but this did not work. What did work, was putting this script in jquery in the head. `$('#sidetextdyn').text($(this).val());` . How could I rephrase that to do 1 / thisval x 96 and then add the letter x on the end. Thanks so much! – Semger Jun 23 '15 at 16:30
  • can you create small snippet with your actual input fields, otherwise as you can check in answer snippet its working properly – vinayakj Jun 23 '15 at 16:42
  • Thanks man, works well! How would I apply this to something like a `

    Text to change

    ` . Also, what about limiting number of decimal places?
    – Semger Jun 23 '15 at 17:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81318/discussion-between-vinayakj-and-semger). – vinayakj Jun 23 '15 at 17:59