Looking for the previous guiStuff?
It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.
References/Tutorials:
Intro Documents:
guiStuff:
::Stuff for the multi-spec coder;
Coding, formats, standards, and other practical things.
Home // JavaScript // Dealing with Forms
<!-- JavaScript
Form Handling
Forms is one of the most important method of communication between the client and the server. HTML forms accept user input and are normally sent to the server for processing the user inputted data. The forms consist of different types of 'user controls' such as a 'Submit button', 'Text box', 'Text area', 'Radio buttons', 'Check boxes' and more.
All these have their own features and uses. For taking only one option from the user we make use of Radio buttons, to take multiple choices we use check boxes, for multiple lines of data we make use of a text area instead of a text box.
<form attribute1="value1" attribute2="value2" ... event1="value3">
Above is the basic form element tag. It can posses various attributes like,
id, class, action, method, style and more. We also make use of event handlers in forms, such as onsubmit - to execute some code when the user submits the form to the server. onreset - when the user resets the form.The action field is the crucial one when it comes to communicating with the server, but at the moment we will not discuss this in any detail since we are dealing only with client side for now. The action field will be the destination where the user data from the form is to be sent for processing or submission.
<script language="JavaScript" type="text/javascript">
function thank_you() {
alert("Thank you" + document.form1.f_name.value + "for submitting your details");
}
</script>
<form name = "form1" action="http://www.domain.com/process_data.php" method="GET" onsubmit="checkname()">
First Name<br />
<input type="text" name="f_name"> <br />
Last Name<br />
<input type="text" name="l_name"> <br />
...
...
...
...
<input type="submit" value="Submit">
</form>
Above is a form which is takes in data from the user, such as 'First Name', 'Last name' and you can have more form elements in it. On clicking submit the form will first call the function thank_you( ) which will diplay an alert to the user for submitting the form and after that the data will be sent to the 'process_data.php' file to the server for any further action.
When a form is loaded with the body, we can also add some features to the form such as focusing the first input field so that the user's attention can be pulled to it.
<body onload="document.form1.f_name.focus()">
This will automatically focus the first text box 'First Name' of the form. One more thing to remember associated with forms is how to refer to them. There are two ways, one is if the form name is specified like how it is above
form1 otherwise you can refer to it as forms[0] if it is the first or only occurrence of a form in the entire page. The subsequent forms, if present, will be numbered in a similar manner like, forms[1], forms[2] and so on. Similarly we can associate the form elements by the array if the element name isn't mentioned.
document.form1.elements[0].value
The above would refer to the first name, if the
f_name wasn't the name for the first text box.Suppose we want two form actions for the same form. In the above form we have used process_data.php to obtain the data from the form whatever the data may be. If there were constraints and conditions on the input value and we had two options as to where to submit the form, then the code will have to be altered.
Let's take for example, that the above form is for an application for a job, and the criteria to process the data is based on the person's gender, so the male forms will have to be submitted to one file for processing while the female to another.
<input type="radio" name="gender" value="m" checked> Male <br />
<input type="radio" name="gender" value="f"> Female <br />
<input type="radio" name="gender" value="f"> Female <br />
Above is the example of the radio buttons, as we would have in the example form.
We can now keep no Action attribute to the form element, but just pass on this to a function
redirect(), which will do our job.
<form onSubmit="redirect(this.gender.value)">
The
redirect() function will look like this:
function redirect(gender) {
if(gender == m)
{document.forms[0].action = http://www.domain.com/process_data_m.php}
else
{document.forms[0].action = http://www.domain.com/process_data_f.php}
}
This will submit our form to the appropriate file for server side scripting.
Resetting a form
There are a couple of ways to reset a form, you can either use the reset in the form control like:
<input type="reset" />
Or you can also make use of a JavaScript function like the one below to reset the first form of the document.
document.forms[0].reset()
Adding items dynamically
Adding new options dynamically is an important part of DHTML. Suppose we have a form in which we select the Country and State we live in. The state will have to be dynamically changed depending upon the selection of the country.
<select name="country_op" onchange="set_state(this)">
<option value="" selected>Choose a your country:</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
...
...
...
</select>
Now if we have the above drop down list, and the user selects his country the function
set_state() will automatically executed. This function will create a fresh dropdown list for the states in that particular country.The dropdown list is dynamically created by the function using the
new operator.
var Opt = new Option( "text", "value" )
We will have to create an array of all the details of the states in all the countries in the function so we can select the correct one.
var country = new Object()
country["usa"] = [{ ... States in the US }]
country["uk"] = [{ ... States in the UK }]
The statements above are included in our script for assigning the states to the respective country objects.
Let’s now have a look at the main function which will be called due to the selection of the country. It will make use of the
country["country_name"] array to obtain the different states of the country.
function set_state(doc) {
var state_op = doc.form.elements["state"];
var ch = doc.options[doc.selectedIndex].value;
var sts = country[ch];
state_op.options[0] = new Option("Choose a State", "");
for (i = 1; i < sts.length; i++) {
state_op.options[i] = new Option(sts[i-1].text, sts[i-1].value);
}
}
The first line creates a new option i.e., the dropdown list for states -
state_op. Then we obtain the value of the choice made by the user, for his country. This variable ch will be the country's name. We can store all the states of the country now in a new variable sts. The next line is to create the first option of the dropdown list, just telling the user to select a state. The for loop then runs for every state in the country and creates the option menu for them.Auto-tabbing is another feature for your forms which helps the user to fill text boxes fast. This can only be done when we know that a particular text box will receive only a particular number of characters. For example if we are entering a 'Key' for a particular software verification and it contains 3 boxes of 4 characters each. After the user enters the first 4 characters the focus should automatically go to the next box of 4 characters. This will save the user time to go and click on that particular box.
<input type="text" name="k1" maxlength="4" onkeyup="a_focus(this, 'k2', event)">
<input type="text" name="k2" maxlength="4" onkeyup="a_focus(this, 'k3', event)">
<input type="text" name="k3" maxlength="4">
Now every time the user enters a character in the box the function
a_focus() is executed to check if 4 characters have reached. If 4 characters are entered then focus will move onto the next box, otherwise the function returns nothing. Here’s an outline of what the function will look like.
function a_focus(doc, nxt, evt) {
//Here we will include the code where we recognize which character was pressed,
//to know more about this please refer to the event handling part.
if (charCode > 31 && doc.forms[0].k1.value.length == 4) {
doc.forms[0].elements[next].focus( );
}
So now, if the character pressed was a legitimate character and the length of the box reaches 4, the focus will move on to the next box.
Disabling/Enabling Buttons
Moving on to the last part, what if we now have to disable the submit button until the user has agreed to certain terms and conditions, the same way we see on plenty of sites on the internet.
We can start with keeping the submit button disabled the and the
terms unchecked.
<input type="Submit" disabled>
<input name="tos" id="tos" type="checkbox" onClick="en_s(this)">
function en_s(frm) {
if(frm.getElementById("tos")==true){
for (i = 0; i < frm.length; i++){
var chk = frm.elements[i];
if (chk.type == "submit")
chk.disabled = false;
}
}
}
The above function will turn the disabled button into an active one.
Return to the JavaScript section, or go the to Main page.