numerical value of number input by user in a text field

后端 未结 4 1242
灰色年华
灰色年华 2020-12-06 19:47

I need to add up two numbers input by the user. To do that, I create two input fields, retrieve values from them , using .val(), in two separate variables and then add them.

相关标签:
4条回答
  • 2020-12-06 20:03

    Use parseInt to convert a string into a number:

    var a = '2';
    var b = '3';
    var sum = parseInt(a,10) + parseInt(b,10);
    console.log(sum); /* 5 */
    

    Keep in mind that parseInt(str, rad) will only work if str actually contains a number of base rad, so if you want to allow other bases you'll need to check them manually. Also note that you'll need to use parseFloat if you want more than integers.

    0 讨论(0)
  • 2020-12-06 20:07

    Number() is the function you want "123a" returns NAN

    parseInt() truncates trailing letters "123a" returns 123

    <input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" />
    
    • jsfiddle
    0 讨论(0)
  • 2020-12-06 20:10

    Either use parseInt (http://www.w3schools.com/jsref/jsref_parseint.asp) or parseFloat (http://www.w3schools.com/jsref/jsref_parsefloat.asp) to convert to a numerical value before adding.

    PS: This is the simple answer. You might want to do some validation/stripping/trimming etc.

    0 讨论(0)
  • 2020-12-06 20:17

    You can use parseInt(...)

    Example:

    var num = parseInt("2", 10) + parseInt("3", 10);
    // num == 5
    
    0 讨论(0)
提交回复
热议问题