Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Change value when value of other input field is changed

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.

like image 764
Anujan Avatar asked Sep 05 '12 18:09

Anujan


1 Answers

A couple of things.

  1. Firstly I'd use the newest version of jQuery if I were you. We're on 1.8 now.

  2. 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/

  3. there were some errors in your code. Note the $("$total_price_amount") part was throwing an error

  4. If you want to only show a set number of decimal point, use .toFixed(). But note that this will return a string.

  5. 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

Here's my updated JSFiddle

http://jsfiddle.net/DigitalBiscuits/QWSQp/71/

And the actual code I used

$(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.

like image 92
OACDesigns Avatar answered Oct 14 '22 16:10

OACDesigns