Search code examples
javascripthtmlclient-side-scripting

Unable to retain the textbox value when the html page is completely loaded


I am trying to set the value of textbox in html page programmatically by javascript. The value is shown-up in textbox and disappears when the page is completely load.

Note : There is no server-side code written.

HTML and Javascript code :

function salutation(){
  	document.getElementById('txt_salutation').value = 'Hi John';
}
   <!DOCTYPE html>
    <html>
    <head>
    	<title>This is website title</title>
    	<script type="text/javascript" src="sample.js"></script>
    </head>
    <body style="background-color:powderblue;">
    	<form id="form1" name="form1">
    		Name:<br>
    		<input id='txt_salutation' type='text'><br>
    	</form>
    	<button id='btn_submit' form = "form1" type="Submit" value="Submit" onclick="salutation()">Submit</button>
    </body>	


    


Solution

  • function salutation(){
        	document.getElementById('txt_salutation').value = 'Hi John';
        }
    <!DOCTYPE html>
        <html>
        <head>
        	<title>This is website title</title>
        	<script type="text/javascript" src="sample.js"></script>
        </head>
        <body style="background-color:powderblue;">
        	<form id="form1" name="form1">
        		Name:<br>
        		<input id='txt_salutation' type='text'><br>
        	</form>
        	<button id='btn_submit'  type="Submit" value="Submit" onclick="salutation()">Submit</button>
        </body>

    i have removed attribute form=form1 from the button. to submit form make new button.