90

Been trying to convert the following to number:

<button class="btn btn-large btn-info" data-votevalue="1">
    <strong>1</strong>
</button>
var votevalue = parseInt($(this).data('votevalue'));

I've also tried Number() but I'm still getting NaN when checking the result. What am I doing wrong?

Here is the complete code:

<div class="span7" id="button-group">
    <div class="btn-group">
        <button class="btn btn-large btn-info" data-votevalue="1"><strong>1</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="2"><strong>2</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="3"><strong>3</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="4"><strong>4</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="5"><strong>5</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="6"><strong>6</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="7"><strong>7</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="8"><strong>8</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="9"><strong>9</strong></button>
        <button class="btn btn-large btn-info" data-votevalue="10"><strong>10</strong></button>
    </div>
</div>
$('#button-group button').each(function() {
    $(this).click(function() {
        $(this).addClass('active');
        var votevalue = parseInt($(this).data('votevalue'));
        var filename = $('.mainimage').data('filename');
        var votes = parseInt($('.mainimage').data('numvotes'));
        var totalscore = parseInt($('.mainimage').data('totalscore'));
        $.ajax({
            type: 'POST',
            url: 'index.php/?category=vote',
            data: {
                "votevalue": votevalue,
                "filename": filename
            },
            success: function() {
                votes++;
                alert(votes);
                var average = ((totalscore + votevalue) / votes);
                $('#vote-incremenet').html(votes);
                $('#display-average').html(average);
                $('#display-average').show();
                $('#button-group button').each(function(){
                    $(this).unbind('click');
                });
            }
        }); // end ajax
    }); // end click
}); // end each
3
  • What does this refer to in the this context? Commented Oct 11, 2012 at 12:30
  • 2
    What you have will work fine, so I can only assume that this does not refer to what you expect. Also, don't forget the radix argument to parseInt! Commented Oct 11, 2012 at 12:31
  • 1
    do you want the value of the data-votevalue property or the text inside the <strong></strong> tags? Commented Oct 11, 2012 at 12:32

9 Answers 9

113

It sounds like this in your code is not referring to your .btn element. Try referencing it explicitly with a selector:

var votevalue = parseInt($(".btn").data('votevalue'), 10);

Also, don't forget the radix.

Sign up to request clarification or add additional context in comments.

2 Comments

I get the correct string when I dont try parsing the variable. So this referece to right object. I posted the complete code in my original post. Maybe you could take a look.
The problem must lie elsewhere in your code then, because the parseInt(votevalue) section works fine: jsfiddle.net/fVJRL
60

You can use parseInt(string, radix) to convert string value to integer like this code below

var votevalue = parseInt($('button').data('votevalue'));
​

DEMO

2 Comments

can't trust parseInt() tried "1,633" it returns "1".
Use parseFloat to convert string to float.
33

Although this is an old post, I thought that a simple function can make the code more readable and keeps with jQuery chaining code-style:

String.prototype.toNum = function(){
    return parseInt(this, 10);
}

can be used with jQuery:

var padding_top = $('#some_div').css('padding-top'); //string: "10px"
var padding_top = $('#some_div').css('padding-top').toNum(); //number: 10`

or with any String object:

"123".toNum(); //123 (number)`

1 Comment

I think your answer is excellent, the only good solution. parseInt or parseFloat doesn't work well If the value is empty "", then I still get NaN. However, I use your solution and add if(!$.isNumeric(this)){ this =0; }, solve everything.
13

For your case, just use:

var votevalue = +$(this).data('votevalue');

There are some ways to convert string to number in javascript.

The best way:

var str = "1";
var num = +str; //simple enough and work with both int and float

You also can:

var str = "1";
var num = Number(str); //without new. work with both int and float

or

var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number

DON'T:

var str = "1";
var num = new Number(str);  //num will be an object. typeof num == 'object'

Use parseInt only for special case, for example

var str = "ff";
var num = parseInt(str,16); //255

var str = "0xff";
var num = parseInt(str); //255

Comments

8

You should just use "+" before $(this). That's going to convert the string to number, so:

var votevalue = +$(this).data('votevalue');

Oh and I recommend to use closest() method just in case :)

var votevalue = +$(this).closest('.btn-group').data('votevalue');

2 Comments

Welcome @expoz - note hit {} in the editor to format a code section, or use 4 spaces in front of code line. Plus you can use single quote ` around code to mark code or package commands e.g. closest(),
I'm pretty sure that's just an exploitation of JavaScript's poor type management. That doesn't seem like a good idea.
7

var string = 123 (is string),

parseInt(parameter is string);

var string = '123';

var int= parseInt(string );

console.log(int);  //Output will be 123.

2 Comments

add details to your answer ?
Exactly the same as this answer, and this answer for that matter.
5

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

Comments

4

You can adding a + before the string without using parseInt and parseFloat and radix, Simply

sample:

var votevalue = +$('button').data('votevalue');

alert(typeof(votevalue));

Comments

0

var votevalue = $.map($(this).data('votevalue'), Number);

1 Comment

it is recommended to provide more context to your answer. Review the guide on how to answer: stackoverflow.com/help/how-to-answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.