简体   繁体   中英

javascript to add 2 numbers in textboxes in asp.net, doesnt work

this is my javascript to get addition of 2 values from 2 textboxes into the third....

its not working...

<script type="text/javascript">

    function calculate(ctrl1, ctrl2, ctrl3) {

        var c1 = document.getElementById(ctrl1);
        var c2 = document.getElementById(ctrl2);
        var c3 = document.getElementById(ctrl3);

        if (c1 != null && c2 != null & c3 != null) {
            c3.value = Number(c1.value) + Number(c2.value);

        }
        document.forms[0].txteanum.focus();

    }    
</script>

in textboxes

<asp:TextBox ID="txtQuantity" runat="server" onblur='javascript:calculate("txtQuantity","txtRate","TxtAmount")'></asp:TextBox>

check my answer here https://stackoverflow.com/a/11624756/1445836

Correct: if (c1 != null && c2 != null & c3 != null)

TO: if (c1 != null && c2 != null && c3 != null) Missing &

To commenters: Sorry I never heard of Number(), since I usually don't work with front-end (especially math in front-end), mostly PHP/C#.

Also, c2 , c3 are <input> 's ?

Maybe You can't get textboxes. Have you tried to give them clientidmode static?

<asp:TextBox ID="txtQuantity" runat="server" onblur='javascript:calculate("txtQuantity","txtRate","TxtAmount")' ClientIDMode="static"></asp:TextBox>

here is the java script which worked for me

function Sum() {
                        var text1 = document.getElementById('<%= TextBox1.ClientID %>');
                        var text2 = document.getElementById('<%= TextBox2.ClientID %>');
                        if (text1.value.length == 0 || text2.value.length == 0) {
                                alert('Textbox1 and Textbox2 should not be empty');
                                return;
                        }

                        var x = parseInt(text1.value);
                        var y = parseInt(text2.value);
                        document.getElementById('<%= TextBox3.ClientID %>').value = x +y;
                }

into the textboxes in .aspx page itself

<asp:TextBox ID="TextBox1" runat="server" onblur="Sum()"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" onblur="Sum()"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

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