Bibek Aryal Bibek Aryal - 2 months ago 8
ASP.NET (C#) Question

How to pass value from <asp:textbox> to javascript function

I am trying to call a

javascript
function from
<asp:textbox>
. My
javascript
function needs to add value from two
<asp:textbox>
, add them and then pass the value to another
<asp:textbox>
. My
javascript
function is as follows

function getAmount() {
var total = $('#ItemRate').val() * $('#ItemQty').val();
$('#ItemAmount').val(total);
}


My
<textbox>
is as follows

<asp:TextBox runat="server" id="ItemRate" />
<asp:TextBox runat="server" id="ItemQty" onchange="javascript:getAmount()" />
<asp:TextBox runat="server" id="ItemAmount" />


Upon running, my console shows the value of total as NaN. How do I solve this one?

Answer

Usually ASP change the ID attribute for each elements which have runat="server" attribute.

So you need other attribute for selecting them, eg. class.

Try this code:

function getAmount() { 
    var total = $('.ItemRate').val() * $('.ItemQty').val();
    $('#ItemAmount').val(total);
}

Html:

<asp:TextBox runat="server" class="ItemRate" id="ItemRate" />
<asp:TextBox runat="server" class="ItemQty" id="ItemQty" onchange="javascript:getAmount()" />  
<asp:TextBox runat="server" class="ItemAmount" id="ItemAmount" />