A simple approach here is to use plain JavaScript
to do all the heavy lifting. Let's take a quick look.
First we set out HTML form
<!DOCTYPE html>
<html>
<body>
<form action="/" method="post" onsubmit="return validateForm();">
Username: <input id="username" type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Now, pay attention to the form
directive which mentions method
, action
and onsubmit
. Let's go over all of those part by part.
I am sure you are completely aware as to what method
and action
do, but for the onsubmit
part, it's linked to a JavaScript function called validateForm()
which is defined as below:
function validateForm() {
var username = document.getElementById( 'username' ).value;
if( !username ) {
return false;
}
return true;
}
This function gets the value of the username
element in the form and returns false
if it's empty, and true
otherwise. What this does is that it tells the event triggers to go forward with submitting the form to action
using the method
verb if the resultant value was true
; if it was false
, however, it just stops the execution. Much like we use the return
keyword to break the current control.
So, in a way, it's triggered before your onClick
handler. IN a very subtle way in the sense that it will not let the form get posted if the validation fails.
Now, of course, you can edit it to suit your needs by just adding a confirm
dialogue as it'll return true
if OK
or YES
is pressed and false
otherwise. But this should give you a good example as to what all you can with the onsubmit attribute in particular, and the event attributes in general.
I hope this answers your question! You can find a fiddle here.