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 the old text.
function func()
{
var text = document.getElementById("text");
text.innerHTML = "Changed";
};
The HTML
<body>
<form>
<input type="submit" value="Add Text" onclick="func()"/>
</form>
<div id="text">
Text to Change
</div>
</body>
What am I missing? I also tried returning 'false' from the function but no luck.
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 the old text.
function func()
{
var text = document.getElementById("text");
text.innerHTML = "Changed";
};
The HTML
<body>
<form>
<input type="submit" value="Add Text" onclick="func()"/>
</form>
<div id="text">
Text to Change
</div>
</body>
What am I missing? I also tried returning 'false' from the function but no luck.
Share Improve this question edited Jan 21, 2014 at 16:19 kassold asked Jan 21, 2014 at 16:13 kassoldkassold 4693 gold badges9 silver badges21 bronze badges3 Answers
Reset to default 14You 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;"/>
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();
});
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