Question

Please excuse my basic query to javascript and html

I am new to javascript and html. I am trying to work with javascript on click and few other things. In below code, am trying to display a text on "onclick" function. I am using an external javascript.

    <!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html"; charset="utf-8" >
        <script type="text/javascript" src="/home/roger/Documents/html/myScript.js"></script>
    </head>
  <body>


    <form>
      First Name: <input type="text" name="first" id="names"/><br>
      Phone Number: <input type="number" name="numb" id="numb"/><br>  
      <button type="button" onclick="verifyText()">Click Me!</button> 
    </form>
  </body>
</html>

Below is my code in myScript.js

function verifyText(){

    document.getElementById("names").innerHTML = "Why not displaying?.";

}

If I put alert in function, pop comes out, but I am unable to figure why innerHTML is not working. Any help will be highly appreciated. Thanks.

Was it helpful?

Solution 3

Use the javascript element.setAttribute('[attr]','string') to save the user input values or input checkbox checks as part of the document innerHTML. The reset() function changes the form input back to its current Attribute setting. Javascript can dynamically change the default input value with the setAttribute therefore, change the user input default value when reset() is clicked or your code reloads it as part of a saved innerHTML.

function update_attribute() {
  var obj = document.getElementById('demo');

  if (obj.type == 'checkbox') {
    if (obj.checked == true) {
      obj.setAttribute('checked', 'checked');
    } else {
      obj.removeAttribute('checked');
    }
  }

  if (obj.type == 'text') {
    obj.setAttribute('value', obj.value);
  }

}
<form id='myform'>

  <label>Text Input</label><br>
  <input type='text' id='demo'>

  <br>
  <br>
  <button type='button' onclick='update_attribute(this)'>Change Attribute</button>
  <button type='reset'>RESET</button>

</form>

OTHER TIPS

You need to set the value, because names is an input field.

document.getElementById("names").value = "Why not displaying?.";

See: http://jsfiddle.net/zrmrx/

names is an <input>. You need to set its value, instead of innerHTML. Try this:

function verifyText(){
    document.getElementById("names").value = "Must display now!";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top