How to submit form with JavaScript and jQuery

It is not always mandatory to submit form requires adding the submit button.

You can submit form using javascript and jQuery where you need to define event on the HTML element – checkbox, radio, select, etc.

In this quick tutorial, I show how you can use JavaScript and jQuery to submit form.

How to submit form with JavaScript and jQuery


Contents

  1. Submit using JavaScript
  2. Submit using jQuery
  3. Demo
  4. Conclusion

1. Submit using JavaScript

Create a <form id='myapp' > and <select > element with languages <option>. Define submitForm() function on change event of <select>.

When it gets triggered then submit the form by calling submit() method and set an option selected using PHP according to the selected value.

Example

<form method='post' action='' id='myform'>
 Select Language : <select name='lang' onchange='submitForm();'> 
  <option value='hindi' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'hindi'){ echo "selected"; } ?> >Hindi</option> 
  <option value='english' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'english'){ echo "selected"; } ?> >English</option>
  <option value='bengali' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'bengali'){ echo "selected"; } ?> >Bengali</option> 
 </select> 
</form>
 
<!-- Script --> 
<script type='text/javascript'> 
function submitForm(){ 
  // Call submit() method on <form id='myform'>
  document.getElementById('myform').submit(); 
} 
</script>

2. Submit using jQuery

Using the above HTML, and use jQuery to submit the <form >.

Example

<form method='post' action='' id='myform'>
 Select Language : <select name='lang' id='lang' > 
  <option value='hindi' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'hindi'){ echo "selected"; } ?> >Hindi</option> 
  <option value='english' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'english'){ echo "selected"; } ?> >English</option> 
  <option value='bengali' <?php if(isset($_POST['lang']) && $_POST['lang'] == 'bengali'){ echo "selected"; } ?> >Bengali</option>
 </select> 
</form>
 
<!-- Script --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type='text/javascript'> 
$(document).ready(function(){
  $('#lang').change(function(){
    // Call submit() method on <form id='myform'>
    $('#myform').submit();
  });
});
</script>

3. Demo

View Demo


4. Conclusion

Whenever you need to submit form without using the submit button then bind an event on the element and call the submit() function.

If you found this tutorial helpful then don't forget to share.

Leave a Comment