Javascript Get Element by Id and set the value

jpo picture jpo · Feb 1, 2013 · Viewed 444.9k times · Source

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. Anyways, 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 please

EDIT

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

Answer

Xiaodan Mao picture Xiaodan Mao · Feb 1, 2013

If myFunc(variable) is executed before textarea is rendered to 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 in the page, and then call myFunc, you can use window.onload or $(document).ready function. Hope it's helpful.