Home

Dynamically Change Form Action Based on Select Option Using jQuery

Published on 7th Feb 2018 in jQuery

In this article we are discussing about how to change form action based on select option using jquery in HTML. Here in this article how you can change form action dynamically selecting by drop down option value. This form action change related with drop down value used in search form with different action as per their selection and a user will go to corresponding result page. It depends on requirement of user what action need in form. You can implement this snippet whenever need dynamic change of form action.
Let us see in detail.
Here first of all we are creating simple html form with select option and form with ID selector. This form action will be change when a user tries to search result by selecting option from drop down. User goes to option related result page.

[caption id="attachment_1001" align="aligncenter" width="624"]Change form action using jquery Change form action using jquery[/caption]

HTML

<form id="searchs" method="post">
<select  id="study" >
<option>Select</option>
<option>School</option>
<option>College</option>
<option>Coaching</option>
</select><br>
<input type="text" class="form-control" placeholder="Search" >
<input id="submit" type="submit" class="submit" value="Submit" />
</form>

Let us see the jquery how we can approach to change dynamic form action on changing select option. In the above form you can see there is no any form action in HTML form where search result will display. This functionality is achieved here by our jquery script.
Below given code will work on change of dropdown option value.

$("#study").change(function(){

On change of dropdown option value we have to get current selected option value to change form action and this is done by below snippet.

var url = $(this).children(":selected").text(); //get the current selected option value

Now we are using here switch method to get action change of form on changing of dropdown option value.
Given below code of jquery will add an action attribute to form as per user selection of option value if case match with current selected value. Have a look.

$("#searchs").attr('action','school.php');

//changing action attribute of form to school.php

Jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
   <script>
  $(document).ready(function(){
   $("#study").change(function(){
   var url =  $(this).children(":selected").text(); //get the selected option value
   switch (url) 
  {
   case "School":
   $("#searchs").attr('action','school.php');
   //changing action attribute of form to school.php
   break;
   case "College":
   $("#searchs").attr('action','college.php');
   break;
   case "Coaching":
   $("#searchs").attr('action','coaching.php');
   break;
   default:
       $("#searchs").attr('action', '#');
   }
   }); 
 }); 
 </script>

Demo

Share It
Stay Connected
Like Us on Facebook