Adding Integers to Javascript

How to add a prime integer to another integer in Javascript?

I get NaN as the value for total.

<script type="text/javascript">
var total = 0;
document.getElementById("dds1").onkeyup = function() {
    total = total + parseInt(this.value,10);
    updateIt();

};

function updateIt() {
//tofixed(2)
    document.getElementById("mySpan").innerHTML = total;
}

But if I do the following:

total = parseInt(this.value,10);

then total matters (integer value).

+3
source share
2 answers

The problem is that you are adding by reading the input value for each key. If the user, for example, presses BACKSPACE to clear the input, the value will be an empty string, which will result in NaN after parseInt. And once you have NaN (in your variable total), you can no longer get rid of it.

Try the following:

document.getElementById('dds1').onkeyup = function() {

    var value = parseInt(this.value, 10);

    if ( !isNaN(value) ) {
        total += value;
        updateIt();    
    }

};

, . , .


:

document.getElementById('dds1').onkeyup = function() {
    var value = parseInt(this.value, 10);

    isNaN(value) && return;

    total += value;
    updateIt();
};

, , , .

+5

javascript . , .

Javascript

<script language="javascript" type="text/javascript">

  function Add() {
    var a, b, c, d;
    a = parseInt(document.getElementById("txtFirstValue").value);

    //
    // If textbox value is null i.e empty, then the below mentioned if condition will 
    // come into picture and make the value to '0' to avoid errors.
    //

    if (isNaN(a) == true) { a = 0; }
    var b = parseInt(document.getElementById("txtSecondValue").value);

    if (isNaN(b) == true) { b = 0; }
    var c = parseInt(document.getElementById("txtThirdValue").value);

    if (isNaN(c) == true) { c = 0; }
    var d = parseInt(document.getElementById("txtFourthValue").value);

    if (isNaN(d) == true) { d = 0; }
    document.getElementById("txtTotal").value = a + b + c + d;
}
</script>

<!-- begin snippet: js hide: false -->

HTML
First Value: <asp:TextBox ID="txtFirstValue" runat="server"
                         onKeyUp="javascript:Add();"></asp:TextBox>

Second Value:<asp:TextBox ID="txtSecondValue" runat="server"
                         onKeyUp="javascript:Add();"></asp:TextBox>

Third Value:<asp:TextBox ID="txtThirdValue" rrunat="server" 
                         onKeyUp="javascript:Add();"><asp:TextBox>

Fourth Value:<asp:TextBox ID="txtFourthValue" runat="server" 
                         onKeyUp="javascript:Add();"></asp:TextBox>

Total = <asp:TextBox ID="txtTotal" runat="server" MaxLength="20" BackColor="#FFE0C0" 
                         Enabled="False" Font- Font-Bold="True" Font-Size="X-Large"> 
            </asp:TextBox>

: http://www.ittutorials.in/source/javascript/scf4/addition-of-multiple-integers-using-javascript.aspx

+1

Source: https://habr.com/ru/post/1788301/


All Articles