简体   繁体   中英

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?

Here is the complete code

Value1: <asp:TextBox ID="tbx1" runat="server"></asp:TextBox>
Value2: <asp:TextBox ID="tbx2" runat="server"></asp:TextBox>
<button onclick="Add()">Add</button><br />

Result:<asp:TextBox ID="tbx3" runat="server"></asp:TextBox>

<script type="text/javascript">

    function Add()
    {

        var x = document.getElementById('<%= tbx1.ClientID %>').value;
        var y = document.getElementById('<%= tbx2.ClientID %>').value;
     document.getElementById('<%= tbx3.ClientID %>').value=parseInt(x)+parseInt(y);
    }
</script>

change value() to val() :

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

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" />

Try with parsing value in float like below code.

  parseFloat("10");

Now multiply both value, also check your id get changed or not in browser doing inspect element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM