Submit Form Conditionally - JavaScript

Submit Form Conditionally - JavaScriptIn the long-gone days of the early Internet, having a form on the website was tantamount to dabbling with "cutting-edge" technologies. Intricate Perl scripts and esoteric CGI scripts were required to process those forms and people used to suffer bouts of cold sweat whenever there manifested a need to use web forms. To create a form-handling script used to be in the realms of MCAs and computer engineers. No longer is it so. The Internet these days is replete with all sorts of form handling scripts, and wherever you choose to host your website, or for that matter even a web page, you can easily deploy a form handling script and start interacting with your visitors.

As the level of interaction goes complex, you require more complicated scripts. One way is to write a single script containing hundreds of lines of code. The action script (that comes within <form ... action="scriptname.php">) encompasses numerous if-then-else conditions, and even within these conditions, there could be zillions of nested if-then-else conditions. After a certain time it becomes a Herculean task to maintain such a form handling script and unless you are an avid documenter, you'll lose the track in no time.

The second way is, write smaller scripts and let the form call them according to the user input. This can save you hundreds of lines of coding, and even if it doesn't, it makes things a lot easier. Suppose you have a form that, along with other things, asks the visitor to which state she belongs. Then, when she clicks the submit button, the action happens according the state she selected. If you have a single script and if you want the script to act according to the individual state, you might end up writing a very large action script. On the other hand, if you specifically write a script for, let us say, California; then you have to write code only centered around California and you can, for the time being, forget about other states.

Javascript lets you submit a single form, conditionally, to different script. Here, we'll learn how to achieve this. First, let us go through a simple form:

<form method="post" name="frm1" onSubmit="javascript: decide_action();" action=""> <input type="radio" name="ch" value="one" /> Choice 1
<input type="radio" name="ch" value="two" /> Choice 2
<input type="radio" name="ch" value="three" /> Choice 3
<input type="submit" name="s1" value="Submit" /> </form>

As you can see, this form displays three radio buttons. The objective is, send the form to a script according to the radio button selected. Since some Javascript action needs to take place once the Submit button is clicked, we invoke decide_action() function through the onSubmit attribute of the <form> tag. Although we include the action attribute, it is left blank. The other form fields are the usual ones. Now let us dive into the cryptic world of the actual script that steers the submission.

<script language="javascript">

function decide_action() { if(check_buttons()==true) { if(document.frm1.ch[0].checked==true) { document.frm1.action="one.php"; } else if(document.frm1.ch[1].checked==true) { document.frm1.action="two.php"; } else { document.frm1.action="three.php"; } document.frm1.submit(); } }

function check_buttons() { var ok=false; for(i=0; i<3; i++) { if(document.frm1.ch[i].checked==true) { ok=true; } } if(ok==false) { alert("Select at least one option."); } return ok; }

</script>

This script contains two functions. The latter one, check_buttons(), makes sure that you select at least one option because if you don't select an option, Javascript doesn't know which form handling script to invoke. It first initializes a variable, ok, to false:

var ok=false;

then through a loop it checks all the radio buttons of the form. As soon as it encounters a radio button that is checked, it assigns the value true to ok

ok=true;

When the function, decide_action() encounters a true:

if(check_buttons()==true)

it first assigns a file name to the action attribute of the object frm1 (the name of the form):

document.frm1.action=file_name;

and then calls the submit() function for that form:

document.frm1.submit();

The script uses multiple if-else decisions to check which radio button was selected, and then submits the form to a form handling script accordingly.

Now, let us take both the functions: check_buttons() and decide_action() to the next level. There can be varied number of radio buttons to check. Why just limit to three radio buttons. The following code not only handles limitless radio buttons, it also assigns the name of the file accordingly (the value of the radio button should be the name of the respective action file).

<script language="javascript">

function decide_action() { var file_destination=check_buttons();

if(file_destination!="") { document.frm1.action=file_destination + ".php"; document.frm1.submit(); } }

function check_buttons() { var val=""; for(i=0; i<document.frm1.ch.length; i++) { if(document.frm1.ch[i].checked==true) { val=document.frm1.ch[i].value; } } if(val=="") { alert("Select at least one option."); } return val; } </script>

This next version of the code is much smaller as it gets rid of multiple if-else statements. Since a particular set of radio buttons is actually an array, we can loop through the array to find out which button is checked. Then we can store the value stored at that index location and return it to the calling function - decide_action(). decide_action() this time uses the value returned, appends the extension ".php", assigns it to the action attribute and then submits it.

This article has walked you through various concepts, but mainly, submitting form to different scripts according to selections made in the form.


Related Articles

  • Form Validation
    Learn the different ways of validating your form with Javascript.
  • Introduction to Javascript for Newbies
    Javascript is a client-side programming language whose processing engine is embedded in web browsers like Internet Explorer, Netscape, Firefox, etc. This enables the processing engine to read and interpret web pages that contain the javascript code when browsing
  • Full Screen
    Javascript allows you to display a page in full screen via a button, the script consists of 2 parts, the first one will be inserted between the and tags is:
  • The Basics- JavaScript Tutorial
    To get started with JavaScript, you will want to be able to see the tag that will set a script apart from the HTML. The tags used to begin and end a script are the tags. The opening tag should appear like this
  • JavaScript: Redirecting URL
    Whenever you want to generate dynamic pages you often have to resort to using some server side scripting language such as PHP or ASP
  • Form Mail via CDONTS
    ASP gives you the power to send mail using the CDONTS mail object. This script will send an email from a user to whichever email address you choose...
  • Close Window
    Add this nifty script to your pop up pages for the users to close them :). Six great styles that should work if done properly.
  • Changing the Background Colour
    Yet another snippet of JavaScript code, folks. This time well be using JavaScript to change a background color with a MouseOver and a mouse click.
  • JavaScript Alerts
    Well, you want to add one of those JavaScript alert boxes that come out of nowhere, dont you? Okay, lets begin with the alert box that just tells the viewer something you want them to know. Heres the alert command:
  • 4 Powerful Features of Javascript Programming Language
    In the community of web developers and surfers, Javascript is highly popular as client side scripting language for web browsers. Lets take a look at some of the features of this language.

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.