I want to change the value of an input field whenever the value of another one is changed.
I've tried for a while and I can't seem to get it to work
<input class="span4 input-big" id="dare_price" name="price" size="30" type="text" onChange="updatePrice()" />
<input class="span4 input-big" id="total_price_amount" readonly="readonly" value=""/>
function updatePrice() {
var price = $("#dare_price").val();
var total = (price + 1) * 1.05;
$("$total_price_amount").val(total);
}
Here's the fiddle.
A couple of things.
Firstly I'd use the newest version of jQuery if I were you. We're on 1.8 now.
I'd also use "keyup" as the event trigger as well as "change". it's just more usable in my opinion. I like to bind events using jQuery also. See http://api.jquery.com/on/
there were some errors in your code. Note the $("$total_price_amount")
part was throwing an error
If you want to only show a set number of decimal point, use .toFixed()
. But note that this will return a string.
input values from text boxes are type string
, so to do mathematical calculations with them you need to parse them to an int
or a float
http://jsfiddle.net/DigitalBiscuits/QWSQp/71/
$(document).ready(function()
{
function updatePrice()
{
var price = parseFloat($("#dare_price").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total_price_amount").val(total);
}
$(document).on("change, keyup", "#dare_price", updatePrice);
});
note that I removed the onChange="updatePrice()"
part from the HTML as it's no longer needed.
Hope this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With