Skip to content Skip to sidebar Skip to footer

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
  • 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

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


    Solution 2:

    $("#dare_price").change(function(){
       var total = Number($this).val()) + ...;
       $('#total_price').val(total);
    });
    

    If you programatically change the values, you need to pipeline them through your method -

    function changePrice(value){
       $('#dare_price').val(value);
       $('#dare_price').trigger('change');
    }
    

    Updated DEMO for this event-driven approach.


    Solution 3:

    Just looks like a typo

    $("$total_price_amount").val(total);
    

    Should be

    $("#total_price_amount").val(total);
    

    Use the '#' to get the id


    Solution 4:

    Just to be safe you should parseFloat() your price. Also, before doing any of this you should make sure it is even a number to begin with! Otherwise you'll get NaN

    function updatePrice() {
        var price = $("#dare_price").val();
        var total = (parseFloat(price) + 1) * 1.05;
        console.log(total);
    
        // Other big problem was the $total_price_amount typo that should of had # instead
        $("#total_price_amount").val(total);
    }​
    

    jsFiddle Demo


    Solution 5:

    Here an example with the change event. You can use events like keydown or -up, whatever suits to your purposes.(The live-method is used for elements created during runtime.)

      $('#first').live("change", (function(){       
                $('#idofinputfield').val('mynewvalue');         
        }))
    

    Post a Comment for "JQuery: Change Value When Value Of Other Input Field Is Changed"