Corey
Corey

Reputation: 267

Why can't I use onsubmit to change innerHTML?

I need to use form fields in an English/Amino Acid Code translater. The code below is simplified to show the problem I'm having. I want to change some text with a javascript function.

If I use an input of type: button with onclick it works.

A submit button with onsubmit in a form changes the text for a split second, then it changes back. I need to use a form for my translation program so how can I make it work?

Extra Credit: Why does it change for a split second with onsubmit?

<html>
<head>
<script type="text/javascript">
function changeTo(text){
    document.getElementById("p1").innerHTML=text;
}
</script>
</head>
<body>
<h1 style="text-align:center;">Change text in an element</h1>
<!--
<form onsubmit="changeTo('Hello World');">
<input type="submit" />
</form>
-->
<input type="button" onclick="changeTo('Hello World');" />
<p id="p1">text</p>

</body>
</html>

Upvotes: 3

Views: 3295

Answers (1)

Tom Gullen
Tom Gullen

Reputation: 61729

It's changing it back because the form is submitting. It posts to the same page, and if you are on a local machine it might be so quick you don't notice. Try:

<form onsubmit="changeTo('Hello World');return false;">
<input type="submit" />
</form>

Return false at the end there will stop the submission process.

Upvotes: 3

Related Questions