Blaine Hurtado
Blaine Hurtado

Reputation: 139

Calculating variable in javascript based on user input

I have the following javascript code:

$(':input').bind('keypress keydown keyup change',function(){
var BetAmount1 = parseFloat($(':input[name="BetAmount"]').val(),10);
var v = '';
if (!isNaN(BetAmount1)){
    v = BetAmount1 * 10;
}
$(':input[name="PotentialGain"]').val(v.toString());
});

I have the following two inputs being echoed through PHP:

<input class="defaultText" type="text" name="BetAmount" id="BetAmount">
<input type="text" name="PotentialGain" id="PotentialGain" />

When the user inputs or changes a BetAmount, I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.

Thanks for your time and consideration.

Upvotes: 0

Views: 191

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185933

This?

$betAmount.on( 'keyup change', function () {
    var gain = 10 * +this.value;
    if ( isNaN( gain ) ) return;
    $potentialGain.val( gain );
});

Live demo: http://jsfiddle.net/Rj64t/

Upvotes: 2

Sergii Bidnyi
Sergii Bidnyi

Reputation: 306

I'd recommend you to paid an attention to Knockout.js lib http://knockoutjs.com/examples/cartEditor.html, it's easy to do such thing with this lib and even more!

Upvotes: 0

Related Questions