user1382306
user1382306

Reputation:

JSON.stringify() <input> values as numbers?

I am using JSON.stringify() on html <input>s to send through a websocket like so:

JSON.stringify({
    numberValue: $('#numberValue').val()
})

but it encodes $('#numberValue').val() as a String.

How can it be encoded as a Number?

Upvotes: 9

Views: 18738

Answers (2)

amatellanes
amatellanes

Reputation: 3735

You can parse the string:

JSON.stringify({
    numberValue: parseInt($('#numberValue').val(), 10);
})

The parseInt() function parses a string and returns an integer.

More info: http://www.w3schools.com/jsref/jsref_parseint.asp

Upvotes: 3

Matt Bryant
Matt Bryant

Reputation: 4961

Convert it to an integer first.

JSON.stringify({
    numberValue: parseInt($('#numberValue').val(), 10);
})

Upvotes: 11

Related Questions