Reputation: 89
I am trying to make this code work, I want the innerHTML
to be changed but It's instantly changing and gets back to its initial state . Any help ?
<!DOCTYPE html>
<html>
<head>
<script>
function click_me(){
alert('fdsfs');
var tweety=document.getElementById('text_this').innerHTML;
alert(tweety);
var text_area="<input type=text value='"+tweety+"'>";
alert(text_area);
document.getElementById('text_this').innerHTML=text_area;
}
</script>
</head>
<body>
<form name="form1">
<table border=1>
<tr>
<td>
<div id="text_this">123</div>
</td>
<td>
<button onclick="click_me();">Edit</button>
</td>
</tr>
</body>
</html>
Upvotes: 0
Views: 108
Reputation: 3411
<!DOCTYPE html>
<html>
<head>
<script>
function click_me(){
alert('fdsfs');
var tweety=document.getElementById('text_this').innerHTML;
alert(tweety);
var text_area="<input type=text value='"+tweety+"'>";
alert(text_area);
document.getElementById('text_this').innerHTML=text_area;
}
</script>
</head>
<body>
<form name="form1">
<table border=1>
<tr>
<td><div id="text_this">123</div></td>
<td><button onclick="click_me();return false;">Edit</button></td>
</tr>
</table>
</form>
</body>
</html>
added a return false statement to the onclick event. without it, the form gets submitted and the page reloads
jsfiddle here
Upvotes: 1
Reputation: 89780
Your form
is getting submitted. Add a return false;
to your button onclick
event.
<button onclick="click_me(); return false;">Edit</button>
Or, make the button type='button'
(This is the better option)
<button onclick="click_me();" type='button'>Edit</button>
The reason is because the button type
is submit
by default if a type
is not specified.
From MDN,
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
Upvotes: 4