ryan
ryan

Reputation: 55

Why does this innerhtml thing go back?

This is my current code. When I click on the button approve....the html heya changes to fred flinstone, but goes back again to heya in 2 seconds. Why so?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="javascript" type="text/javascript">
function button()
{
    var a = document.getElementById('approve');
    document.getElementById('p').innerHTML= 'Fred Flinstone';
}
</script>

<body>
<form>
<p id="p">heya</p>
<input type="submit" id='approve' value="approve" onclick="button()"/>
<input type="submit" id="reject" value="reject"/>
</form>

</body>
</html>

Thanks.

Upvotes: 0

Views: 1979

Answers (2)

Mike Dinescu
Mike Dinescu

Reputation: 55760

That's because the submit button causes the page to reload, effectively undoing your changes to the DOM.

If you change the type of the input element to "button" instead of "submit" it will work fine.

<input type='button' id='approve' value='approve' onclick='button()'/>

Please note that in doing this, the button will not be posting the form anymore. If that's what you want then you will need to have code on the server side to modify the rendered page to reflect your changes.

Upvotes: 3

mtkopone
mtkopone

Reputation: 6443

This also works:

<input type="submit" id='approve' value="approve" onclick="button(); return false;"/>

Upvotes: 1

Related Questions