0

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?

2
  • What's wrong with the code you show? Commented May 1, 2015 at 2:02
  • 1
    works fine here jsfiddle.net/mjc6fq97/2 Commented May 1, 2015 at 2:02

2 Answers 2

3

The 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...

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I understand! Thanks. I don't actually need the form to submit at this point, so just switching the type to "button" was all that was needed.
2

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.

1 Comment

Thanks -- yes, this all that was required. Changing it from a "submit" to a "button" type fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.