user5049245
user5049245

Reputation:

Get Integer from HTML text to JavaScript

I have a text field like this:

<input id="num" type="text" style="width:10px"/>

I am trying to retrieve it from JavaScript as follows:

var numofnodes =parseInt(document.getElementById('num').value,10);

It is giving "", and i tried like this

var numofnodes =document.getElementById('num').value

But still I am getting "".

Upvotes: 2

Views: 11975

Answers (4)

Divins Mathew
Divins Mathew

Reputation: 3186

Hmm, surprisingly enough, no one mentioned the event's built-in property for this.

event.target.valueAsNumber

will give the value as a number for inputs with type number without any conversions.

Upvotes: 0

user2575725
user2575725

Reputation:

Problem seems that you are trying to read the value on page load, i.e. textbox isn't having any value given, hence you get blank:

var numofnodes = parseInt(document.getElementById('num').value, 10);
alert(numofnodes);
<input id="num" type="text" style="width:10px" />

Try with value attribute for default no. of nodes:

var numofnodes = parseInt(document.getElementById('num').value, 10);
alert(numofnodes);
<input id="num" type="text" style="width:10px" value="100" />

Upvotes: 3

Esa Hannila
Esa Hannila

Reputation: 1318

I tried your code, and for me it works correctly.

<input id="num" type="text" style="width:10px;" value=100 />

added value into attribute

$(document).ready(function() {
    // print into console as int
    var numofnodes =parseInt(document.getElementById('num').value,10);
    console.log(numofnodes);

    // print into console as string
    var numofnodes =document.getElementById('num').value 
    console.log(numofnodes);
});

Upvotes: 0

Đinh Carabus
Đinh Carabus

Reputation: 3494

parseInt either returns an integer or NaN, it shouldn't be a "". How do you output the value that you get? Your code seems to works fine for me:

<input id="num"  type="text" style="width:100px"/>
<button id="b">log value</button>

...

document.getElementById("b").onclick = function()  {
  console.log( parseInt(document.getElementById('num').value, 10) );
}

http://codepen.io/anon/pen/LVMzxr?editors=101

Upvotes: 0

Related Questions