Javascript Get Element by Id and set the value

534,012

Solution 1

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.

Solution 2

Given

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

then

function setText(id,newvalue) {
  var s= document.getElementById(id);
  s.innerHTML = newvalue;
}    
window.onload=function() { // or 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.onload=function() {
  setValue("This-is-the-real-id","Hello there");
}

will do what you want

function setContent(id, newvalue) {
  var s = document.getElementById(id);
  if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;
  else s.innerHTML = newvalue;
  
}
window.addEventListener("load", function() {
  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="">

Solution 3

<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>

Solution 4

Coming across this question, 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");

Though unlikely helpful for the original questioner, this addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset()-proof.

I hope this may help others.

(Or me in half a year when I've forgotten about js quirks...)

Solution 5

For each element type, you can use 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 example here!

Share:
534,012

Related videos on Youtube

jpo
Author by

jpo

Updated on February 04, 2020

Comments

  • jpo
    jpo over 4 years

    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

    • Anthony Grist
      Anthony Grist over 11 years
      Let's see where you call the function (which, judging from the code you've provided, doesn't have a name).
    • mplungjan
      mplungjan over 11 years
      what is variable? And how do you call the unnamed function?
    • Pointy
      Pointy over 11 years
      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 + "]");
    • Dennis
      Dennis over 11 years
      Please show an example of this happening at jsfiddle.net - what you are asking doesn't really make sense.
  • jpo
    jpo over 11 years
    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
  • mplungjan
    mplungjan over 11 years
    We need to see the html and the event handler (onclick or whatever)
  • jbabey
    jbabey over 11 years
    Inline event handlers are bad practice.
  • jpo
    jpo over 11 years
    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.
  • Xiaodan Mao
    Xiaodan Mao over 11 years
    @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.
  • jpo
    jpo over 11 years
    My code look like this @Html.HiddenFor(m => m.myfield, new{id = "myId"}) <input type="button" onclick="javascript: myFunc(myID)" value="button"/>.
  • jpo
    jpo over 11 years
    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?
  • Xiaodan Mao
    Xiaodan Mao over 11 years
    @jpo In onclick="javascript: myFunc(myID)", myID should be wrapped by single quotes.
  • Xiaodan Mao
    Xiaodan Mao over 11 years
    @jpo When will you set the id of textarea? Before page loads or after page loads? Before the button is clicked or after the button is clicked?
  • jpo
    jpo over 11 years
    It is set before the button is clicked.
  • Xiaodan Mao
    Xiaodan Mao over 11 years
    @jpo It's weird, is myID wrapped by single quotes? Or your id is not set successfully. Have you checked the id with the web developer tool like firebug? Does it exist?
  • mplungjan
    mplungjan over 5 years
    The javascript: label is completely unnecessary