Change label text using JavaScript
JavascriptHtmlLabelInnerhtmlJavascript Problem Overview
Why doesn't the following work for me?
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>
Javascript Solutions
Solution 1 - Javascript
Because your script runs BEFORE the label exists on the page (in the DOM). Either put the script after the label, or wait until the document has fully loaded (use an OnLoad function, such as the jQuery ready()
or http://www.webreference.com/programming/javascript/onloads/)
This won't work:
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
<label id="lbltipAddedComment">test</label>
This will work:
<label id="lbltipAddedComment">test</label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
This example (jsfiddle link) maintains the order (script first, then label) and uses an onLoad:
<label id="lbltipAddedComment">test</label>
<script>
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
});
</script>
Solution 2 - Javascript
Have you tried .innerText
or .value
instead of .innerHTML
?
Solution 3 - Javascript
Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:
<label id="lbltipAddedComment"></label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
Solution 4 - Javascript
Use .textContent
instead.
I was struggling with changing the value of a label as well, until I tried this.
If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir
as shown on this question: https://stackoverflow.com/questions/9633835/how-can-i-log-an-html-element-as-a-javascript-object
Solution 5 - Javascript
Using .innerText
should work.
document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
Solution 6 - Javascript
Here is another way to change the text of a label using jQuery:
<script>
$("#lbltipAddedComment").text("your tip has been submitted!");
</script>
Check the JsFiddle example
Solution 7 - Javascript
Try this:
<label id="lbltipAddedComment"></label>
<script type="text/javascript">
document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>
Solution 8 - Javascript
Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.
It will work.