Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...