Programming jQuery jQuery Tutorial #8: How to Change HTML Values ​​with jQuery

jQuery Tutorial #8: How to Change HTML Values ​​with jQuery

jQuery Tutorial #8: How to Change HTML Values ​​with jQuery

In our previous tutorial on learning jQuery, we learned how to retrieve HTML values ​​with jQuery. This time I will discuss how to change the values of an HTML element with jQuery.

How to Change HTML Values with text() and html() Methods

To change the value of an HTML element, it’s very similar to retrieving an element. The difference is, we insert an argument into the text() and html() methods . Let’s take a look at an example:

In the code above, I have 2 <p> tags , each with the id paragraph1 and paragraph2 . When the “ Change! ” is clicked, I change the content of each paragraph with the text() and html() methods .

Notice how it is used which is very similar to our previous tutorial (retrieving HTML values). If the text() and html() methods are filled with arguments, this means that we want to change the content of the HTML element, not take its value. Concepts like this are commonly used in jQuery.

Code:

That is, look for an HTML tag with id=”paragraph1″, then change the content of the tag with the string: “<b>#jQuery</b> is Amazing…”.

Likewise with the second command:

That is, look for an HTML tag with id=”paragraph2″ , then change the content of the tag with the string: “<b>#jQuery</b> is Amazing…” .

As you can see, the html() method will process the HTML tags that are in the text. In the example above, the #jQuery text will be bold because of the <b> tag effect. As for the text() method, the text will be displayed as-is, where the <b> tag is considered as plain text, not an HTML tag.

How to Change HTML Form Values with jQuery val() Method

For HTML forms, we can also change the existing value, or rather change the value attribute value of the form object. The way to use it is almost the same as the text() and html() methods but this time we use the val() method. Here’s an example:

When the Change! Clicked, the value of the <input type=”text”> tag will be changed to “Techbriefers” .

By combining ways of retrieving and changing the value of HTML elements, we can create a program code that will dynamically swap depending on user input. Here’s an example:

When the Copy button on click event is triggered, the command var value = $(“#text_box”).val() is used to retrieve the contents of the form and is stored as a value variable. This value variable is then moved into the paragraph via the $(“#target”).html(value) command .

Please type any text into the form, then press the Copy button . Fill in the form will appear in the paragraph below.

In this jQuery tutorial, we have covered how to change and copy HTML element values. But what if what I want is to add a new element to the HTML? We’ll learn in the next tutorial: How to Add new elements to HTML with jQuery.

Leave a Reply