jQuery adding 2 numbers from input fields

前端 未结 6 1503
梦谈多话
梦谈多话 2020-12-16 15:29

I am trying to add two values of alert boxes but I keep getting a blank alert box. I don\'t know why.

$(document).ready(function(){
    var a = $(\"#a\").va         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 16:10

    Adding strings concatenates them:

    > "1" + "1"
    "11"
    

    You have to parse them into numbers first:

    /* parseFloat is used here. 
     * Because of it's not known that 
     * whether the number has fractional places.
     */
    
    var a = parseFloat($('#a').val()),
        b = parseFloat($('#b').val());
    

    Also, you have to get the values from inside of the click handler:

    $("submit").on("click", function() {
       var a = parseInt($('#a').val(), 10),
           b = parseInt($('#b').val(), 10);
    });
    

    Otherwise, you're using the values of the textboxes from when the page loads.

提交回复
热议问题