Change Form Action Based on Select Option Using jQuery

Hi guys, I hope you all are good and rocking. Today I am sharing another simple tutorial for all our lovely new devs, we will see how we can dynamically change form action based on user selection in dropdown options. There are times when you need this for example in a search form you may ask user where to search in blog section, product section or entire website? Another example would be of a registration form where you want user to select his department and based on that you redirect him to that particular department page. So there would be various situations where you will need to dynamically change form action based on either select box option or radio button option selected by user.


Live Demo

Let’s see how easily we can do this. We have a simple form which will ask user his name, email and department. Based on his department selection we will take him to that department page. Sounds good? Let’s start the fun with simple jQury code.

We have a simple HTML form:

<form id="myform" method="post">
 <label>Name :</label>
 <input type="text" class="name" /></br></br>
 <label>Email :</label>
 <input type="email" class="email" /></br></br>
 <label>Department :</label>
 <select id="dept">
 <option >--Select Your Department--</option>
 <input id="submit" type="submit" class="submit" value="Submit" />

You can see, we have not set any action for this form. Yes we will have our jQuery code do that. Now when user will select different values from “Department” dropdown jQuery will capture that value and based on the value received it will assign corresponding page as form action’s attribute value. Simple enough!

Lets see main code in our js file, below line will capture the selected text in department dropdown list:

var selected_dept = $(this).children(":selected").text();

Once we have this value we can assign different form action with the below code:


Now lets see our complete script.js:


 // change fn on dept id
 var selected_dept = $(this).children(":selected").text(); // Get the selected option value

 case "CSE":
 // dynamically changing action attribute of form to cse.html

 case "ECE":
 // dynamically changing action attribute of form to ECE.html

 case "ME":
 // dynamically changing action attribute of form to ME.html

 case "CE":
 // dynamically changing action attribute of form to CE.html
 // Default action

That’s all. It was simple enough. This can also be done using javascript. In this post select box was used to chose different departments, we can also do this with radio buttons. Based on radio buttons selected change the form action. Now you can easily do that 🙂 Share this tutorial to help our new developers friends.

About sanjeev

Dreamer, Blogger and Thinker. I love to help people in solving their problems. You can also join me HERE

Related posts: