[javascript] document.getElementById().value doesn't set the value

Browser is chromium (under ubuntu)

This is a chunk of code: (of course) The alert messages shows the right value. but the points element doesn't get the right value, it actually gets empty. Can anybody tell me why?

Here's how points element is defined.

<input type='number' id='points' value='0'/> 

and here is how javascript code is supposed to populate it.

alert(request.responseText);

document.getElementById("points").value=request.responseText;

This question is related to javascript html

The answer is


The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

According to my tests with Chrome:

If you set a number input to a Number, then it works fine.

If you set a number input to a String that contains nothing but a number, then it works fine.

If you set a number input to a String that contains a number and some whitespace, then it blanks the input.

You probably have a space or a new line after the data in the server response that you actually care about.

Use document.getElementById("points").value = parseInt(request.responseText, 10); instead.


Refer below Code Snip

In HTML Page

<input id="test" type="number" value="0"/>

In Java Script

document.getElementById("test").value=request.responseText;// in case of String 
document.getElementById("test").value=new Number(responseText);// in case of Number

Try using ,

$('#points').val(request.responseText);

The problem is clearly not with the javascript. Here's a quick snippet to show you the working of the code.

document.getElementById('points').value = 100;

http://jsfiddle.net/eqTm2/1/

As you can see, the javascript perfectly assigns the new value to the input element. It would be helpful if you could elaborate more on the issue.