Search code examples
javascripthtmlasp.netgridviewonblur

Using javascript to calculate price in asp.net


I'm using textbox in gridview and want to calculate values through js in textbox my code is not showing any error. I want to multiply quantity with rate and get total price.

function totalise(price, rate, qt) {
    var qty = window.document.getElementById(qt).value;
    var rate = window.document.getElementById(rate).value;
    var price = rate;
    price.value = rate * qty;
}

<asp:TextBox ID="txtStonePrice" runat="server" onblur=" totalise(this)" ></asp:TextBox>

Solution

  • First, youre not actually passing in rate and qt to your totalise function, so you can't look them up.

    Second, try using parseFloat or parseInt on those (rate.value and qty) values, otherwise they will be strings.

    Third, rate already equals the value of the element with ID==rate, so after you've addressed the other 2 things I mentioned, you'll want something like this:

    (note I'm ignoring some bad naming conventions. also, you should probably do some error checking to make sure youre actually getting the elements you look up by Id)

    function totalise(price, rate, qt) {
        var qty = window.document.getElementById(qt).value;
        var rate = window.document.getElementById(rate);
        var price = rate;
        price.value = parseFloat(rate.value) * parseFloat(qty);
    }