Plus Arithmetic Operation

后端 未结 7 1665
庸人自扰
庸人自扰 2020-12-07 06:43

I\'ve tried use Plus Arithmetic Operation to calculate 2 input text type number values, but my result was the values are \"together\", like that:

相关标签:
7条回答
  • 2020-12-07 06:58

    http://jsfiddle.net/BLGLe/

    <script type="text/javascript">
       function cal(){
        var plus = parseInt(document.getElementById('plus').value),
            plus1 = parseInt(document.getElementById('plus1').value);
        var x = plus + plus1;
        var result = document.getElementById('result');
        if(result.value == ""){
         result.innerHTML = "?";
        }
        else{
         result.innerHTML = x;
        }
      }
    </script>
    
    <input type="text" id="plus" /> + <input type="text" id="plus1" /> = <span id="result"></span>
    
    0 讨论(0)
  • 2020-12-07 07:01

    You can try this:

    function cal(){
        var plus = +document.getElementById('plus').value,
            plus1 = +document.getElementById('plus1').value;
        var x = plus + plus1;
        var result = document.getElementById('result');
        if(isNaN(plus) || isNaN(plus1) || result.value == ""){
         result.innerHTML = "?";
        }
        else{
         result.innerHTML = x;
        }
      }
    

    Notice the + signs that convert the two string values to numbers.

    0 讨论(0)
  • 2020-12-07 07:01

    parseInt is what missing from your code .. you need to parse it as integer barring which just the concatenation operation takes place , so you can either do this

    var plus = parseInt(document.getElementById('plus').value, 10),
    plus1 = parseInt(document.getElementById('plus1' ).value, 10);
    

    or

    var x = parseInt(plus , 10) + parseInt(plus1 , 10) ;
    
    0 讨论(0)
  • 2020-12-07 07:04

    You need to parse them to an Integer type:

    var x = parseInt(plus) + parseInt(plus1);
    

    Then you can use isNaN() to determine whether it was a valid operation or not: (note that I'm checking the value of x not of the resulting output)

    if(isNaN(x)){
     result.innerHTML = "?";
    }
    else{
     result.innerHTML = x;
    }
    

    Living demo: http://jsfiddle.net/4KB5Y/3/

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

    All values you get from input elements in the DOM are going to be strings.
    Javascript uses + both for concatenating strings and for addition.
    To make it clear you want to add numbers instead of concatenating strings, you need to make sure your values are numbers:

    parseInt(plus, 10) + parseInt(plus1, 10)
    

    Yes, this is one of the most basic and often encountered gotchas in Javascript.

    0 讨论(0)
  • 2020-12-07 07:09
    var plus = parseInt(document.getElementById('plus').value, 10),
        plus1 = parseInt(document.getElementById('plus1').value, 10);
    

    This will do what you want.

    0 讨论(0)
提交回复
热议问题