I have the following javascript function that updates a text within a div when a button is clicked (using an onclick() event) It works, but it immediately changes back to th
You are actually submitting the form. Prevent that by adding return false to the onclick attribute:
<input type="submit" value="Add Text" onclick="func(); return false;"/>
You are using input type="submit" inside Form tag , clicking this button will refresh the same page .
try
<input type="button" value="Add Text" onclick="func()"/>
<div id="text">
Text to Change
</div>
or remove form tag
The form submits causing the page to refresh and reload the original content.
Try returning false on a form submit handler to prevent the default action:
<form onsubmit="return false;">
If I may suggest, avoid inline event handlers altogether. Instead use the modern events API with the much nicer addEventListener
:
<body>
<form id='mainForm'>
<input type="submit" value="Add Text"/>
</form>
<div id="text">
Text to Change
</div>
</body>
Javascript:
var form = document.getElementById("mainForm");
var text = document.getElementById("text"); // probably not a very good id!
form.addEventListener("submit",function(e){
text.innerHTML = "Hello!";
e.preventDefault();
});