Javascript | How to change form action dynamically

Author - Kritika Sood

Suppose on click of an element we want to change the form action URL. In this example, we are assuming a textbox in which user will type a value and then click search magnifying glass icon. On click of search icon we want to check if textbox is empty or not. If it is empty we want to change action. URL

HTML for search box:

//by default action is for textbox not empty

<form id="coursesearch" action="your URL" method="post">
    <div id="searchcontainer">
   	 <fieldset id="box" class="coursesearchbox invisiblefieldset">
   		 <input id="magnify" type="submit" value="Go">
   		 <input type="text" id="coursesearchbox" size="30" name="search" value="">
   	 </fieldset>
   </div>
</form>

Javascript for changing the action URL:

$('#magnify').click(function(){  //click event handler for search icon
if($('#coursesearchbox').val() == ' '){   //if search box is empty
$("#coursesearch").attr("action","");    //empty the action of the box defined in HTML                 				                                                     
var URL=" new URL";                      //define new target URL
$("#coursesearch").attr("action",URL);  //give new action to searchbox
}                                                                 
});

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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