Javascript, parseInt() on value from getElementByID doesn't work

mwaning

I've been stuck trying to figure this out for hours. What on earth is going wrong? If I understand correctly, the value you get from getElementById is a string, so what I'm trying is to parse it into an int (in order to use it for sums), but when I try to print it as an int, it tells me NaN.

The expected result is to print the value 123 back in the test div, replacing the text Click, but instead it only prints NaN.

<div id="test" value="123" onclick="testFunction()">Click</div>

function testFunction() {
        var strVal = document.getElementById('test').value;
        var intVal = parseInt(strVal);
        document.getElementById('test').innerHTML = intVal;
}
Phix

There's no inherent value property for div. You'll need to access the attribute directly:

function testFunction() {
  var strVal = document.getElementById('test').getAttribute('value')
  var intVal = parseInt(strVal);
  document.getElementById('test').innerHTML = intVal;
}
<div id="test" value="123" onclick="testFunction()">Click</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

parseInt doesn't work

document getelementbyid setting value doesn't work

javascript doesn't work in IE (getElementById)

getElementById doesn't work at all

parseInt doesn't work well in a loop

Why doesn't document.getElementById not work?

document.getElementById doesn’t work

getElementsByClassName doesn't work, but getElementById does?

VBA getElementById doesn't work for button

document.getElementById doesn't work

Why doesn't creating video var from jquery work and from getElementById does?

Javascript: input and button. Function doesn't work -> Document.getElementById is not a function

Javascript getElementById() works for a text box but doesn't work with radio buttons or drop-down selectors

Why Jquery $(#); doesn't work but Javascript document.getElementById works fine?

Why doesn't Integer.parseInt("1")++ work in Java?

why doesn't Integer.parseInt method work for splitted strings?

Why querySelector work and $() or document.getElementById doesn't work with checkboxes?

Javascript if doesn't work

Why document.getElementById() command doesn't work on my code?

Display value in input field doesn't work with JavaScript

Javascript number comparaison with negative value doesn't work

Return value from main() in Rust doesn't work

setting the onclick value from <script> doesn't work

Get value from simple JSON data doesn't work?

Setting value to objects' property from its function doesn't work

Firebase Order By a Date Value from Today Doesn't Work

Post a value from php page to the same page doesn't work

Opencv (JavaScript) Mat from Array doesn't work

trigger an automatic download from javascript doesn't work on page load