Reputation: 1099
I am trying to change the text in a div, but am not having very much luck. From scrounging around I have come up with the following:
<script type="text/javascript">
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>"
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
}
</script>
<div id="Key">Hi there</div>
<form name="DemoForm" action="">
<button onclick="UpdateElapsed()">Update</button>
</form>
however after I click the update the words "Hi there" remain there.. If I click update a bunch of times every once in a while, it will say "You Clicked update". I realize this is probably very simple, but I'm new and stuck. Please be kind :)
Upvotes: 1
Views: 78
Reputation: 544
Try this:
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>"
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
}
<div id="Key">Hi there</div>
<form name="DemoForm" action="">
<button onclick="UpdateElapsed();return false;">Update</button>
</form>
Upvotes: 0
Reputation: 7591
If you give the button an id and add the eventlistener through javascript it works.
CODE:
html:
<div id="Key">Hi there</div>
<button id="my_btn">Update</button>
javascript:
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>"
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
}
document.getElementById('my_btn').addEventListener('click', UpdateElapsed);
Upvotes: 0
Reputation: 2907
You have two solutions:
1. You can remove the form, and the code will work fine.
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>";
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
}
<div id="Key">Hi there</div>
<button onclick="UpdateElapsed()">Update</button>
2. Add return false
in the UpdateElapsed
function
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>";
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
return false;
}
<div id="Key">Hi there</div>
<form name="DemoForm" method="get">
<button onclick="return UpdateElapsed()">Update</button>
</form>
Upvotes: 1
Reputation: 385
Its working fine for me.. Could you show your entire code? Sorry this was not a comment, you need 50 rep to comment so i had to put it as an answer.
Upvotes: 1
Reputation: 368
<script type="text/javascript">
function UpdateDiv(fieldname, text) {
document.getElementById(fieldname).innerHTML = "<strong>" + text + "</strong>"
}
function UpdateElapsed() {
UpdateDiv("Key", "You Clicked Update");
}
</script>
<div id="Key">Hi there</div>
<button onclick="UpdateElapsed()">Update</button>
Upvotes: 2