107

I have a JavaScript function to which I pass a parameter. The parameter represents the id of an element (a hidden field) in my web page. I want to change the value of this element.

function myFunc(variable) { var s = document.getElementById(variable); s.value = 'New value' } 

When I do this, I get an error that the value cannot be set because the object is null. But I know the object is not null because I see it in the HTML code generated by the browser.

Anyway, I tried the following code to debug

function myFunc(variable) { var x = variable; var y = 'This-is-the-real-id' alert(x + ', ' + y) var s = document.getElementById(x); s.value = 'New value' } 

When the alert message shows up, both parameters are the same, but I still get the error. But everything works fine when I do

 var s = document.getElementById('This-is-the-real-id'); s.value = 'New value' 

How can I fix this?

The element for which I am setting the value is a hidden field and the id is set dynamically, as the page loads. I have tried added this in the $(document).ready function, but it did not work.

4
  • 2
    Let's see where you call the function (which, judging from the code you've provided, doesn't have a name). Commented Feb 1, 2013 at 15:09
  • what is variable? And how do you call the unnamed function? Commented Feb 1, 2013 at 15:09
  • When you do a diagnostic alert() or console.log() in cases like this, you should always wrap values with some marker characters so you can tell whether there are stray space characters in the strings. So: alert("[" + x + "], [" + y + "]"); Commented Feb 1, 2013 at 15:12
  • Please show an example of this happening at jsfiddle.net - what you are asking doesn't really make sense. Commented Feb 1, 2013 at 15:17

8 Answers 8

92

If myFunc(variable) is executed before the textarea is rendered to the page, you will get the null exception error.

<html> <head> <title>index</title> <script type="text/javascript"> function myFunc(variable) { var s = document.getElementById(variable); s.value = "new value"; } myFunc("id1"); </script> </head> <body> <textarea id="id1"></textarea> </body> </html> <!-- Error message: Cannot set property 'value' of null --> 

So, make sure your textarea does exist on the page, and then call myFunc. You can use the window.onload or $(document).ready function.

Sign up to request clarification or add additional context in comments.

8 Comments

I create the hidden field, and then create the button which executes the function that sets the value of the hidden field. However, the id is set dynamically. I tried added this function in the $(document).ready function but the same issue arises.
@jpo If the id is set dynamically, you also should make sure that myFunc is called after the id is set. You can try to call myFunc in the function which sets the id.
My code look like this @Html.HiddenFor(m => m.myfield, new{id = "myId"}) <input type="button" onclick="javascript: myFunc(myID)" value="button"/>.
The function is only called when the button is clicked and this only happens after the page loads. How else can I ensure that everything happens before the button is clicked?
@jpo In onclick="javascript: myFunc(myID)", myID should be wrapped by single quotes.
|
29

Given

<div id="This-is-the-real-id"></div> 

then

function setText(id, newvalue) { var s = document.getElementById(id); s.innerHTML = newvalue; } window.addEventListener("load", function() { setText("This-is-the-real-id", "Hello there"); } 

will do what you want


Given

<input id="This-is-the-real-id" type="text" value=""> 

then

function setValue(id, newvalue) { var s = document.getElementById(id); s.value = newvalue; } window.addEventListener("load", function() { setValue("This-is-the-real-id", "Hello there"); } 

will do what you want.

Example of a function that can handle either:

const setContent = (id, newvalue) => { var s = document.getElementById(id); s[s.matches("input")?"value":"innerHTML"] = newvalue; // use value if input, else innerHTML } window.addEventListener("load", function() { // important, especially if script is before the elements setContent("This-is-the-real-id-div", "Hello there"); setContent("This-is-the-real-id-input", "Hello there"); })
<div id="This-is-the-real-id-div"></div> <input id="This-is-the-real-id-input" type="text" value="">

2 Comments

Exactly what I thought. But my id and set dynamically. But I used the same idea. But when I function is called, the document cannot find the element with the specified id
We need to see the html and the event handler (onclick or whatever)
8

No answer brought up the possibility of using .setAttribute() in addition to .value():

document.getElementById('some-input').value="1337"; document.getElementById('some-input').setAttribute("value", "1337"); 

This addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset()-proof.

1 Comment

Rude? Or did I just miss an SO rule here?
4

Use:

<html> <head> <script> function updateTextarea(element) { document.getElementById(element).innerText = document.getElementById("ment").value; } </script> </head> <body> <input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;" onKeyUp="updateTextarea('myDiv')" /> <br> <textarea id="myDiv" ></textarea> </body> </html> 

Comments

3

For each element type, you can use a specific attribute to set value.

E.g.:

<div id="theValue1"></div> window.document.getElementById("theValue1").innerText = "value div"; <input id="theValue2"></input> window.document.getElementById("theValue2").value = "value input"; 

You can try the example here!

Comments

1

Try it like below. It will work...

<html> <head> <script> function displayResult(element) { document.getElementById(element).value = 'hi'; } </script> </head> <body> <textarea id="myTextarea" cols="20"> BYE </textarea> <br> <button type="button" onclick="displayResult('myTextarea')">Change</button> </body> </html> 

1 Comment

Inline event handlers are bad practice.
-1

I think the problem is the way you call your JavaScript function.

Your code is like so:

<input type="button" onclick="javascript: myFunc(myID)" value="button"/> 

myID should be wrapped in quotes.

2 Comments

The javascript: label is completely unnecessary
They didn't show how they call the function, what makes you think this is the problem?
-2

const setContent = (id, newvalue) => { var s = document.getElementById(id); s[s.matches("input")?"value":"innerHTML"] = newvalue; // use value if input, else innerHTML } window.addEventListener("load", function() { // important, especially if script is before the elements setContent("This-is-the-real-id-div", "Hello there"); setContent("This-is-the-real-id-input", "Hello there"); })
<div id="This-is-the-real-id-div"></div> <input id="This-is-the-real-id-input" type="text" value="">

3 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Don't use innerHTML if you don't expect the newvalue to be html text. You'll want to set textContent instead.
This has nothing to do with the problem, which is that document.getElementById(id) is returning null.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.