Skip to content
Advertisement

JavaScript window.onload

<!DOCTYPE html>  
<html>  
<head>  

    <script type="text/javascript" >
                 
               function changeTitle() {                      
                  if (document.getElementById('myText').value === "") {                     
                     document.getElementById('title').innerHTML = "Welcome to JavaScript";  
                     alert("Enter a valid text title");  
                     return;                      
                  } else {                        
                  document.getElementById('title').innerHTML = document.getElementById('myText').value;  
                  
                  }  
               }                                
      </script>           
</head>          
<body>  
    <h1 id="title">Welcome to JavaScript</h1>      
    <p> Hello! This is my first JavaScript example on Microsoft Visual Studio Express Edition 2013.</p>          
    <p>  
        <input id="myText" type="text"/>  
        <input type="submit" onclick="changeTitle();" value="Click me!"/>  
    </p>      
</body>  
</html>  

In this little example, I want to save the initial innerHTML of the h1 tag (id=title) to a variable after loading the page for the first time.

And then instead of the document.getElementById('title').innerHTML = 'Welcome to JavaScript' which is inside the if statement, I want to substitute that above mentioned variable with the phrase “Welcome to JavaScript“.

My main intention is, wwhenever some one leaves the textbox (id=myText) blank and click on the submit button, script should replace the innerHTML of the h1 tag (id=title) to the initial value that was there in the first page load and pop out that alert box. (Maybe user has changed the innerHTML of the h1 before, but the script should replace it to the initial value that was there in the first page load).

Advertisement

Answer

You can declare a hidden input.

<input type="hidden" id="initialTitle" value=""/>

and populate the hidden field value via body onload JS function like.

function setInitialTitle() { document.getElementById('initialTitle').value = document.getElementById('title').innerHTML }


<body onload="setInitialTitle()";>

And in changeTitle() function rewrite if block as.

document.getElementById('title').innerHTML = document.getElementById('initialTitle').value;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement