Introduction with JQUERY - Setting Content

Guest Posts Paolo Nikko Nuñal

In the last article, we talk about on how to access HTML DOM elements, this time around, you'll get to learn on how you can set them using the same methods, html(), text() and val() method. This is very useful in situations where you would be adding text, html code or attributes to specific portions of an HTML document.

As a recap, here are the functions of the following methods.

text() - Is used to set or return the text content of selected elements.

html() - Is used to set or return the content of selected elements that includes HTML markup.

val () - Is used to set or return the value found on the form fields.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$("#btn-text").click(function(){
 $("#p1").text("Im a text using the set text() method");
 });
 $("#btn-html").click(function(){
 $("#p2").html("<b>BOLD set using the html()</b>");
 });
$("#btn-value").click(function(){
 $("#input1").val("I'm a value set by a button");
});
</script></head>
<body>
<p id="p1>Paragarph 1</p>
<p id="p2>Paragraph 2</p>
<input id="input1" value="" type="text">


<button id="btn-text">Set Text</button>
<button id="btn-html">Set HTML</button>
<button id="btn-value">Set Value</button>
</body>
</html>


Clicking on the "SET TEXT" will call the paragraph with the id "#p1" and will change the value to "Im a text using the set text() method");. Clicking on the "SET HTML" will call the paragraph with the id "#p2" and will change the text with an html code in bold "<b>BOLD set using the html()</b>". Lastly, clicking on the button "SET VALUE" will set the input form with the value "I'm a value set by a button".

Setting the values of specific DOM elements is useful, most especially if you are getting data from the database and want to show the results on your existing HTML page. Most especially for update pages or you want to edit specific portions by adding HTML tags on existing sections.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here