I am having trouble using .innerHTML within a javascript function called by clicking a button. For a brief flickering second I can see that the function is called, and the text changed, but then the text reverts.
<html>
<head>
</head>
<body>
<form>
<input type="submit" value="Change the Text" onClick="change()">
</form>
<div id="ToBeChanged"> Hello, World </div>
<script>
function change(){
document.getElementById("ToBeChanged").innerHTML = "New Text";
};
</script>
</body>
</html>
Of course, if I just use the .innerHTML outside of a function, it changes the text without any problems and does not revert to the old text. Is there a way to use .innerHTML to change text from the the onClick function? Or is there another way I should be acplishing this task?
I am having trouble using .innerHTML within a javascript function called by clicking a button. For a brief flickering second I can see that the function is called, and the text changed, but then the text reverts.
<html>
<head>
</head>
<body>
<form>
<input type="submit" value="Change the Text" onClick="change()">
</form>
<div id="ToBeChanged"> Hello, World </div>
<script>
function change(){
document.getElementById("ToBeChanged").innerHTML = "New Text";
};
</script>
</body>
</html>
Of course, if I just use the .innerHTML outside of a function, it changes the text without any problems and does not revert to the old text. Is there a way to use .innerHTML to change text from the the onClick function? Or is there another way I should be acplishing this task?
Share Improve this question asked May 1, 2015 at 2:00 RMooreRMoore 1831 gold badge3 silver badges9 bronze badges 2- What's wrong with the code you show? – jfriend00 Commented May 1, 2015 at 2:02
- 1 works fine here jsfiddle/mjc6fq97/2 – Abdul Ahmad Commented May 1, 2015 at 2:02
2 Answers
Reset to default 3The text reverts back because you have an input type=submit
which basically is calling the javascript function and then submitting the form, which reloads the page.
You need to prevent the submission of the form. Something like:
onClick="change(); return false;"
However, perhaps your button shouldn't be type submit to begin with...
Oftentimes, when someone says that code in a submit button event handler does not work, the issue is that the button is causing the page to be reloaded, thus making you think that your code isn't working. In fact, your code is probably working, but then the page reloads immediately so you never see the code's effect.
If that is indeed what is happening, you can prevent the page reload by changing your button to a regular button (not a submit button).
<input type="button" value="Change the Text" onClick="change()">
You could also leave the button as a submit button and prevent the default behavior for the button, but if you don't intend to submit a form, then better to just stop making it a submit button in the first place and just make it a regular button.