Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change label text using JavaScript

Why doesn't the following work for me?

<script>     document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!'; </script> <label id="lbltipAddedComment"></label> 
like image 662
phil crowe Avatar asked Dec 20 '10 10:12

phil crowe


People also ask

How do I change a dynamic label?

To dynamically update the Label widget, we can use either config(**options) or an inline configuration method such as for updating the text, we can use Label["text"]=text; for removing the label widget, we can use pack_forget() method.

How do you use labels in JavaScript?

JavaScript label is a statement used to prefix a label as an identifier. You can specify the label by any name other than the reserved words. It is simply used with a colon (:) in code. A label can be used with a break or continue statement to control the flow of the code more precisely.


1 Answers

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> 
like image 129
Konerak Avatar answered Oct 13 '22 23:10

Konerak