JavaScript - Form Handling


We can handle forms in different ways like validating, submitting, altering, updating form data, etc. using JavaScript.

Form Validation

Form validation normally occurs at the server, after the client had entered all the necessary data and then pressed the Submit button.

If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.

JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.

  • Basic Validation First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
  • Data Format Validation Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate checks to ensure that the data entered is the data you are expecting.

Code snippet

function validateForm() {
   var x = document.forms["myForm"]["fname"].value;
   if (x == "") {
      alert("Name must be filled out");
      return false;
   }
}
validateForm();

In the above code, we have declared a function validateForm that checks if our form inputs are valid and input are properly fille, If not it will alert us to fill the missing data.

Following is the output of the above code:

Name must be filled out

Form Submit

After validating the form, we can submit the form data to the server. We can use methods like submit() and reset() to submit and reset the form data.

Code snippet

<form id="myForm" action="">
   First name: <input type="text" name="fname"><br>
   Last name: <input type="text" name="lname"><br><br>
   <input type="button" value="Submit" onclick="myFunction()">
</form>
<script>
document.getElementById("myForm").submit();
document.getElementById("myForm").reset();
</script>

In the above code, we have used the submit() method to submit the form data and reset() method to reset the form data.

Conclusion

We can handle forms easily in JavaScript. Validation becomes a lot more easier and faster with JavaScript. We can also submit and reset the form data using JavaScript.

Advertisements