We're going to create form validation through the use of an alert to tell the user what's wrong with the form's submission.
First off, we'll need to place the following code inside our anonymous function after our previously added code:
$("#form1 input[type=submit]").click(function(e) { e.preventDefault(); var msg_error = ""; $("#form1 input[type=text]").each(function() { if ($(this).val() == "") { msg_error += $(this).attr("placeholder") + "can't be left blank.\n"; } }); if (msg_error) { alert(msg_error); } else { alert("Form submitted successfully!"); } });
We used the click()
handler on our submit button to trigger our form validation checking. For the sake of this example, we used preventDefault()
so that when we click on our submit button, the URL hash doesn't change. Make sure to remove this line when you launch this code into the wilds of the Internet.