How to submit form with JavaScript and jQuery

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

You can do this with any other elements e.g. checkbox, radio, select, etc. using Client side script.

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

How to submit form with JavaScript and jQuery


Contents

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

 

1. 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. jQuery

Take the above example, 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

Select a language.


 

4. Conclusion

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

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *