Text, HTML & Values
Changing what a page says is the most common job in front-end code: a total updates, a status message appears, a form field is cleared. jQuery has three methods for this: .text() for plain text, .html() for HTML markup, and .val() for form fields.
In this lesson you will use all three, learn the one safety rule that matters most (never put user input into .html()), and see the matching plain DOM properties: textContent, innerHTML and value.
text(): plain text
.text() with no argument returns the text inside the matched elements, with every tag stripped out. With an argument, it replaces the contents of every matched element with that text.
$("#total").text(); // read: "₹1,250"
$("#total").text("₹1,499"); // write
$(".badge").text(3); // numbers are fine; they become "3"
// Plain JavaScript
document.querySelector("#total").textContent; // read
document.querySelector("#total").textContent = "₹1,499"; // writeWhatever you pass to .text() is shown exactly as typed. If the string contains <b>, the visitor sees the characters <b>, not bold text. That is what makes .text() safe for anything that came from a user.
One detail: as a getter, .text() joins the text of all matched elements, so $("li").text() gives every item's text run together. Most other getters read only the first element.
html(): markup
.html() with no argument returns the HTML inside the first matched element. With an argument, it parses the string as HTML and builds real elements from it, exactly like setting innerHTML.
$("#note").html("Delivery by <strong>Friday</strong>"); // shows bold text
// Plain JavaScript
document.querySelector("#note").innerHTML = "Delivery by <strong>Friday</strong>";This is useful for HTML that you wrote. It is dangerous for anything else. Run this preview of a review form. The visitor's input is pre-filled with something an attacker might type:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text() vs html()</title>
<style>
.box { border: 1px solid #ccc; padding: 0.5rem; margin: 0.4rem 0; min-height: 1.5rem; }
input { inline-size: 100%; max-inline-size: 32rem; }
</style>
</head>
<body>
<label for="review">Your review</label>
<input id="review" value='Tasty chole! <img src="nope.png" onerror="$('#alarm').text('Attacker code just ran!')">'>
<button id="preview">Preview</button>
<p>With <code>.text()</code> (safe):</p>
<div class="box" id="safe"></div>
<p>With <code>.html()</code> (unsafe):</p>
<div class="box" id="unsafe"></div>
<p id="alarm"></p>
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"></script>
<script>
$("#preview").on("click", function () {
const review = $("#review").val();
$("#safe").text(review); // shown as characters
$("#unsafe").html(review); // parsed: the onerror code runs
});
</script>
</body>
</html>Click Preview. The safe box shows the raw characters. In the unsafe box, the browser creates a real <img>, the image fails to load, and its onerror code runs: a warning line appears below the boxes. Writing a line of text is harmless, but code injected the same way can read a logged-in user's data or send requests in their name. This attack is called XSS (cross-site scripting).
val(): form fields
.val() reads and writes the current value of form controls. It handles each kind of control sensibly:
| Control | .val() returns | Plain JavaScript |
|---|---|---|
<input>, <textarea> | the typed text | el.value |
<select> | the chosen option's value | el.value |
<select multiple> | an array of chosen values (empty array if none) | [...el.selectedOptions].map((o) => o.value) |
| checkbox / radio | its value attribute, ticked or not | el.value; use el.checked for ticked |
As a setter, .val("Pune") selects the matching option in a select, and .val(["a", "b"]) ticks the checkboxes or options whose values are in the array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reading form values</title>
</head>
<body>
<p><label>Name <input id="name" value="Meera"></label></p>
<p>
<label>City
<select id="city">
<option>Jaipur</option>
<option selected>Kochi</option>
<option>Pune</option>
</select>
</label>
</p>
<p>
<label>Subjects (Ctrl+click for many)
<select id="subjects" multiple>
<option selected>Maths</option>
<option>Biology</option>
<option selected>Computer Science</option>
</select>
</label>
</p>
<p><label><input type="checkbox" id="hostel" value="yes"> Needs hostel</label></p>
<button id="read">Read values</button>
<button id="reset">Fill sample data</button>
<pre id="out"></pre>
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"></script>
<script>
$("#read").on("click", function () {
const data = {
name: $("#name").val().trim(),
city: $("#city").val(),
subjects: $("#subjects").val(), // an array
hostel: $("#hostel").prop("checked"), // true or false
};
$("#out").text(JSON.stringify(data, null, 2));
});
$("#reset").on("click", function () {
$("#name").val("Farhan");
$("#city").val("Pune");
$("#subjects").val(["Biology"]);
$("#hostel").prop("checked", true);
});
</script>
</body>
</html>Notice that the checkbox uses .prop("checked"), not .val(). A checkbox's value is the fixed text in its value attribute; whether it is ticked is a separate property. You will learn the difference between attributes and properties in Attributes, Properties & Data.
Setting with a function
All three setters also accept a function. jQuery calls it once per element with the index and the old value, and uses whatever you return:
// Add a rupee sign to every price that does not have one yet
$(".price").text(function (index, oldText) {
return oldText.startsWith("₹") ? oldText : "₹" + oldText;
});
// Plain JavaScript
document.querySelectorAll(".price").forEach((el) => {
if (!el.textContent.startsWith("₹")) el.textContent = "₹" + el.textContent;
});Common mistakes
- Using
.html()because "it also works for text". It does, until someone types<. Default to.text(). - Reading a checkbox with
.val(). You get itsvalueattribute even when it is unticked. Use.prop("checked")or.is(":checked"). - Forgetting that
.val()returns a string.$("#qty").val() + 1gives"21"for a value of 2. Convert withNumber()first. - Expecting
.html()to read every element. It returns only the first element's HTML.
Key points
.text()/textContentread and write plain text and are safe for user input..html()/innerHTMLparse HTML; use them only with markup you wrote..val()/valuehandle form fields; a multiple select returns an array in jQuery.- Ticked state of checkboxes and radios is the
checkedproperty, not the value. - Setters accept a function
(index, oldValue)to compute a new value per element.
Exercise
Make a small "bill" page: an input for a dish name, an input for its price, a button, and a <ul id="bill">. When the button is clicked, read both values with .val(), add a new line to the list showing "Dish: ₹price" using .text() on a new <li> (create it with $("<li>")), then clear both inputs. The dish name must be shown safely even if someone types HTML.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bill</title>
</head>
<body>
<input id="dish" placeholder="Dish">
<input id="price" type="number" placeholder="Price">
<button id="add">Add</button>
<ul id="bill"></ul>
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"></script>
<script>
$("#add").on("click", function () {
const dish = $("#dish").val().trim();
const price = Number($("#price").val());
if (!dish || !price) return;
$("<li>").text(dish + ": ₹" + price).appendTo("#bill");
$("#dish, #price").val("");
});
</script>
</body>
</html>$("<li>") creates an empty list item, .text() fills it safely, and $("#dish, #price").val("") clears both inputs in one call.
Quick Quiz
1. Which method is safe for showing a comment typed by a visitor?
.text() never parses HTML, so tags and event attributes are shown as plain characters.
2. What does $("#subjects").val() return for a <select multiple> with two options chosen?
For multiple selects, jQuery's .val() returns an array of values.
3. How do you check whether a checkbox is ticked in jQuery?
The ticked state is the checked property; .val() returns the fixed value attribute.
4. What is the plain JavaScript equivalent of $("#city").val("Pune") on a single select?
Setting value selects the option with that value.
Learn jQuery with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
