Set or Assign Value to a Label dynamically using jQuery

jQuery provides two separate methods to set or assign values to a label dynamically. The methods are “text()” and “html()”. Both the methods have distinct features. You can use either of these two methods to assign a value to a label.

Also Read: How to Assign or Set Values Dynamically to a Label using JavaScript

Using jQuery text() Method

The text() method allows us assign or add plain text values. The method treats the contents as text. Here’s an example.

<label id="lblName"></label>
The Script using text()
    $(document).ready(function () {
        $('#lblName').text('Hello, I am Arun Banik');

Try it Yourself

Using jQuery html() Method

The html() method on the other hand, allows us to write HTML codes, along with the text (or any string value). Use this method when you want to add style to your text (or the entire sentence) or you want to add a link (<a>…</a>) with the text etc.

In the example below, I have added the <b>… </b> tags along with my name to show the value in bold.

    $(document).ready(function () {
        $('#bt').click(function () {
            $('#lblName').html('Hello, I am <b> Arun Banik </b>');

Try it Yourself

Note: If you add any markup or HTML code to the text() method, it will show the content along with the HTML codes, as it is. For example, if I want show what HTML codes were added to the content, I’ll do this.

$('#lblName').text('<u>Hello</u>, I am <b> Arun Banik </b>');


<u>Hello</u>, I am <b> Arun Banik </b>

Or, you can use JavaScript methods like innerHTML and innerText to assign values to the labels, dynamically. It is simple, does not require any library, and hence improves the performance of your app on the web.

Thanks for reading.

Previous - How to Show a Text over an Image at Mouse Location using jQuery

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!