One method for every control
.val() is the jQuery way to work with form values. With no argument it reads the current value; with an argument it sets it. Unlike .attr("value"), it always reflects what the user has typed or chosen.
Text inputs and textareas
<input id="name" value="Asha">
<textarea id="bio">Likes hiking.</textarea>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
console.log("name:", $("#name").val());
console.log("bio:", $("#bio").val());
$("#name").val("Asha Verma");
console.log("after set:", $("#name").val());
console.log("attribute is still:", $("#name").attr("value"));
</script>name: Asha
bio: Likes hiking.
after set: Asha Verma
attribute is still: AshaThe last line shows the difference from the previous lesson: .val() changed the live value, while the value attribute still holds the starting value from the HTML. Always use .val() for form values.
Values are always strings. If you need a number, convert it: Number($("#qty").val()). Use .val().trim() to drop accidental spaces before you check whether a field is empty.
Select lists
<select id="city">
<option value="">Choose a city</option>
<option value="pune">Pune</option>
<option value="jaipur" selected>Jaipur</option>
<option value="kochi">Kochi</option>
</select>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
console.log("value:", $("#city").val());
console.log("label:", $("#city option:selected").text());
$("#city").val("kochi");
console.log("now:", $("#city").val(), "/", $("#city option:selected").text());
</script>value: jaipur
label: Jaipur
now: kochi / Kochi.val()returns the chosen option'svalueattribute (or its text if it has novalue).- To get the visible label instead, read the selected option's text.
.val("kochi")selects the option whose value iskochi. If no option matches, nothing is selected.
Multiple selects
A <select multiple> can have several chosen options, so .val() returns an array:
<select id="skills" multiple size="4">
<option value="html" selected>HTML</option>
<option value="css">CSS</option>
<option value="js" selected>JavaScript</option>
<option value="sql">SQL</option>
</select>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
console.log("chosen:", $("#skills").val());
$("#skills").val(["css", "sql"]);
console.log("after set:", $("#skills").val());
$("#skills").val([]);
console.log("none chosen:", $("#skills").val());
</script>chosen: ["html", "js"]
after set: ["css", "sql"]
none chosen: []Pass an array to choose several options. With nothing chosen, you get an empty array, so .val().length is a safe test.
Radio buttons
Each radio button has its own value, so reading .val() on the whole group gives you only the first one's value, chosen or not. Here the second radio is chosen, yet the group reads as free. Select the checked radio first:
<label><input type="radio" name="plan" value="free"> Free</label>
<label><input type="radio" name="plan" value="pro" checked> Pro</label>
<label><input type="radio" name="plan" value="team"> Team</label>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
console.log("wrong:", $("input[name=plan]").val());
console.log("chosen:", $("input[name=plan]:checked").val());
$("input[name=plan]").val(["team"]); // choose by value
console.log("now:", $("input[name=plan]:checked").val());
</script>wrong: free
chosen: pro
now: teamTo choose a radio from code, pass an array with the value to .val() on the whole group, or set .prop("checked", true) on the one you want.
Checkboxes
A checkbox's .val() is its value attribute, which does not change when it is ticked. Use .prop("checked") for the state, and .map() to collect the values of all ticked boxes:
<label><input type="checkbox" name="extra" value="wifi" checked> Wi-Fi</label>
<label><input type="checkbox" name="extra" value="breakfast"> Breakfast</label>
<label><input type="checkbox" name="extra" value="parking" checked> Parking</label>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const extras = $("input[name=extra]:checked").map((i, el) => el.value).get();
console.log("extras:", extras.join(", "));
console.log("breakfast ticked?", $("input[value=breakfast]").prop("checked"));
</script>extras: wifi, parking
breakfast ticked? falseSetting a value does not fire change
When a user changes a field, the browser fires a change event. When your code sets a value, it does not. If other code listens for changes, trigger the event yourself:
<select id="country"><option>India</option><option>Nepal</option></select>
<p id="note"></p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#country").on("change", function () {
$("#note").text("Shipping to " + $(this).val());
console.log("change handler ran");
});
$("#country").val("Nepal"); // handler does not run
console.log("after .val():", $("#note").text() || "(empty)");
$("#country").val("Nepal").trigger("change"); // now it runs
</script>after .val(): (empty)
change handler ranReading a whole form
To collect every field at once, .serialize() turns a form into a URL-encoded string and .serializeArray() into an array of name/value pairs. Only fields with a name attribute are included, and unticked checkboxes are left out. The Ajax section uses both to send forms to a server.
Common mistakes
- Using
.attr("value")to read what the user typed. Use.val(). - Reading a radio group without
:checked. - Using
.val()to check a checkbox's state. Use.prop("checked"). - Forgetting values are strings:
"5" + 1is"51". Convert withNumber(). - Expecting change handlers to run after setting
.val()from code.
Exercise
Build a form with a quantity input (number) and a select of prices. When a Total button is clicked, multiply the two and show the result in a paragraph.
Show one possible answer
<input id="qty" type="number" value="3">
<select id="price"><option value="50">Basic (50)</option><option value="80" selected>Plus (80)</option></select>
<button id="total">Total</button>
<p id="out"></p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#total").on("click", function () {
const total = Number($("#qty").val()) * Number($("#price").val());
$("#out").text("Total: " + total);
console.log(total);
});
</script>240Key points
- .val() reads the current value of an input, textarea or select; .val(value) sets it.
- For a select with multiple, .val() returns an array of the chosen values.
- For radio buttons, read the checked one: $("input[name=size]:checked").val().
- Setting .val() from code does not fire a change event; call .trigger("change") if other code must react.