jQueryintermediate 8 min
Read, validate and submit forms: val(), serialize(), the submit event and preventDefault.
How to read form values with .val(), check them before sending, stop the normal page reload, and show friendly error messages.
Forms are how users give your site information. Validating in the browser gives instant feedback and saves a round trip to the server.
.val() reads the value of an input, select or textarea. .val("text") sets it..is(":checked"). For a radio group use $("input[name=plan]:checked").val()..on("submit", fn) runs when the form is submitted. Call event.preventDefault() to stop the browser reloading the page, so you can handle it yourself (for example with AJAX)..serialize() turns all the fields into a URL-style string such as name=Asha&email=a%40b.com..trim() through $.trim or the native String.trim() removes extra spaces..text() and .addClass("error"), and clear them on the next attempt.event.preventDefault() so the page does not reload..val().trim() reads each field and removes extra spaces..is(":checked") tests the checkbox..serialize() builds the form data string, which is ready to send with AJAX. Fields without a name attribute are skipped, so here it is empty: add name="..." to the inputs to include them.Try submitting an empty form, then a valid one. Add name="name" and name="email" to the inputs to see them appear in the serialized string.
preventDefault(), so the page reloads and your messages vanish..attr("checked") to read a checkbox. Use .is(":checked")..val(), test checkboxes with .is(":checked").submit event and preventDefault().Next: should you still use jQuery at all?
<style>
.error { color: #b91c1c; font-size: 14px; }
input.bad { border: 2px solid #b91c1c; }
</style>
<form id="signup">
<p><input id="name" placeholder="Name"> <span class="error" id="nameErr"></span></p>
<p><input id="email" placeholder="Email"> <span class="error" id="emailErr"></span></p>
<p><label><input type="checkbox" id="agree"> I agree</label></p>
<button type="submit">Join</button>
</form>
<p id="result"></p>
<script>
$("#signup").on("submit", function (event) {
event.preventDefault();
$(".error").text("");
$("input").removeClass("bad");
const name = $("#name").val().trim();
const email = $("#email").val().trim();
let ok = true;
if (name === "") {
$("#nameErr").text("Please enter your name");
$("#name").addClass("bad");
ok = false;
}
if (email.indexOf("@") === -1) {
$("#emailErr").text("Email needs an @");
$("#email").addClass("bad");
ok = false;
}
if (!$("#agree").is(":checked")) {
ok = false;
$("#result").text("Please tick the box");
}
if (ok) {
$("#result").text("Welcome, " + name + "! " + $(this).serialize());
}
});
</script>