最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding numbers together - Stack Overflow

programmeradmin0浏览0评论

I have this Jquery code and i need to add the var data and a number together...

$('div[name=price]').html("");  
    $.post("getprice.php", { unit: $('input[name=property]:checked').val() , date: $('#car').val() + $('#smh').val()  } ,function(data){
        $('div[name=price]').html(data + 1);
        $('#bprice').val(data);
});

But data equals 499 but it just displays as 4991 when it should say 500

Thanks

Lee

I have this Jquery code and i need to add the var data and a number together...

$('div[name=price]').html("");  
    $.post("getprice.php", { unit: $('input[name=property]:checked').val() , date: $('#car').val() + $('#smh').val()  } ,function(data){
        $('div[name=price]').html(data + 1);
        $('#bprice').val(data);
});

But data equals 499 but it just displays as 4991 when it should say 500

Thanks

Lee

Share Improve this question edited Jun 27, 2011 at 16:44 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Jun 27, 2011 at 16:41 LeeLee 1,2804 gold badges18 silver badges37 bronze badges 1
  • 1 I was close to make a joke about jQuery, addition and plugins... – Felix Kling Commented Jun 27, 2011 at 16:44
Add a ment  | 

5 Answers 5

Reset to default 4

You have two options, since Javascript is defaulting to treating it as a string:

$('div[name=price]').html(parseInt(data, 10) + 1);

$('div[name=price]').html(data*1 + 1);

EDIT: I'm not sure I picked the right field you were talking about, but the idea is you have to convert a string to a numbers, and that is done by parseInt or multiplying by 1

You need to coerce data to a number by writing +data.

Use parseInt:

$('div[name=price]').html(parseInt(data, 10) + 1);

try this

$('div[name=price]').html(parseInt(data, 10) + 1);

try this : $('div[name=price]').html(data * 1 + 1);

Using the *1 tries to modify the type from string to number in JS.

发布评论

评论列表(0)

  1. 暂无评论