If you want to convert "8"
to 8
:
var age = +$("#age").val();
This will convert the value in #age
to a number. You don't need jQuery to do the conversion, but you can use jQuery's .val()
for taking the value out of <input>
.
If you want to convert "eight"
to 8
:
First of all, change the type from number
to text
.
If you want to convert a number written in English to a number, you can use an Object
.
var nums = {
"one": 1,
"two": 2,
...
};
var age = nums[$("#age").val().toLowerCase()];
However this is greatly not recommended because you will have to create an entry for every number you accept.
A better approach would be separating the ones and the tens so on and so forth, but you will have to deal with special cases such as "eleven", "fifty"
and invalid inputs: https://stackoverflow.com/a/12014376/283863
Fun fact
Interestingly, it is possible to do the other way around (Number to Word) in modern browsers:
var number = 10;
number.toLocaleString("zh-Hans-CN-u-nu-hanidec"); //it supports many languages,
//including Chinese.