user1022585
user1022585

Reputation: 13641

javascript input field to number

I need to convert an input field into a number. So if the input field is empty, or contains letters, the number would be 0.

This doesn't work:

var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold < 1) {

I've tried parseInt on it too, can't seem to work it. Any advice?

Upvotes: 0

Views: 3011

Answers (4)

aquatorrent
aquatorrent

Reputation: 841

this will checks whether the it's a number or not, and change the value to 0 if it's not.

var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold.search(/[^0-9]/)>=0)
{
       // not a number
       trade_gold = 0;
}

Upvotes: 0

Ehsan Khodarahmi
Ehsan Khodarahmi

Reputation: 4922

var trade_gold = 0;
try{
    trade_gold = parseInt(document.getElementById('trade_gold').value, 10);
}catch(e){}

Upvotes: 0

jbabey
jbabey

Reputation: 46647

var value = document.getElementById('trade_gold').value;

value = parseInt(value, 10);

// parseInt will return NaN if the conversion failed
if (isNaN(value)) {
    value = 0;
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Upvotes: 0

user1106925
user1106925

Reputation:

var val = document.getElementById('trade_gold').value,
    trade_gold = parseFloat(val) || 0;

Upvotes: 3

Related Questions