Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  23] [ 6]  / answers: 1 / hits: 15662  / 9 Years ago, fri, may 1, 2015, 12:00:00

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 accomplishing this task?


More From » onclick

 Answers
10

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.


[#66801] Wednesday, April 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;