Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Chris

Chris Avatar

******
Head Coder

19,519


June 2005
Form Manipulation

Note: Before reading this tutorial, you should have a general understanding of most of the possible uses of items in a form. All general and simple items. Also, I will not be doing anything with uploads. Nothing really to do with them. I also will not cover radios, since they're a mixture between a select and a checkbox and can be figured out easy enough if you understand them. Lastly, for all examples we will be pretending that they are inside the following form:

<form name="testForm" id="testForm" action="index.php" method="get">
  <!-- Form items here -->
</form>






Accessing the Form and Form Items
This is a basic concept that needs to be explained. First off, we need to assign a name to the form we want to access. The example form already has the name of "testForm," so we'll take advantage of that. We're going to access it via the document object.

var theform = document.testForm;

Now that we have the form, we want to access an element inside the form. Each element in a form should have a name assigned to it, though sometimes they won't. In this case, let's assume we want to access the element with the name "formitem1."

var theform = document.testForm;
var formitem1 = theform.formitem1;


Now that we've got access to the form item, we could perform any operation on it that we want. Let's say we want to find a element who's value matched "foo," but we didn't know the name of it. We'd use the "elements" array.

var theform = document.testForm;
var eles = document.testForm.elements;
for(var a=0;a<eles.length;a++){
  if(eles[a].value.match(/foo/i)){
     var theele = eles[a];
     break;
  }
}


Make sure to note that this assumes that an element would match "foo," otherwise you could encounter errors.

Now, it is possible to perform a similar search through forms. Let's say we know a form contains "bar" in the name, but we aren't sure of the exact name. We could search through the forms property of the document object.

var tosearch = document.forms;
for(var a=0;a<tosearch.length;a++){
  if(tosearch[a].name.indexOf("bar") != -1){
     var theForm = tosearch[a];
 break;
  }
}


I'm not going too far into detail on these, as they aren't a fairly important part of this tutorial, despite being helpful.

Note: There are numerous ways to access a form or form elements. I've only explained a few.

One last thing I want to mention before moving into the actual tutorial. You can use the "form" property of a form element to obtain the form for that element. For example, "checkbox.form" would return the form that contains a checkbox.





Input - type="text"
Let's start off with the most basic, of the basic. An input with type="text". For this example, we'll be using this input:

<input type="text" value="Default Value" name="inputtext" id="inputtext" maxlength="15" />

First off, we're going to cover the basics of grabbing information that a user enters. Whenever a user enters information, it is sent into the "value" property of the input. So, taking the default input, if we alerted the value of document.testForm.inputtext.value, we'd get "Default Value" since that's the current value.

Let's take a look at making a simple "Click on this and the text inside disappears, but if blank reappears." In this case, we're going to work with simple events and we'll be making this similar to something that one might use if a search box.

<input type="text" value="Search" name="searchBox" id="searchBox" maxlength="100" />
<script type="text/Javascript">
var theBox = document.testForm.searchBox;
theBox.onfocus = function(){
  if(this.value == "Search"){
     this.value = "";
  }
}
theBox.onblur = function(){
  if(this.value.length == 0){
     this.value = "Search";
  }
}
</script>


Now, let's break down the code. First off, we have our input itself. Then, we move to the script tag. The third line grabs the search box itself. Now we get to where we assign the events that will manage the clearing of and filling in of the "Search" text. We're using two basic events functions: onfocus and onblur. Onfocus activates whenever the object in question obtains the focus of the user. Onblur activates whenever the object in question loses the focus of the user. (Note that it doesn't activate if the item did not already have the focus of the user.) We assign two simple events and then in the events, we check specific properties of the value, and then change value depending on if the check returns true. This is a basic, and quite straightforward method of doing a box that auto-clears itself. You could also have assigned the events inline in the input tag. These inputs also support the "disabled" property via javascript (input.disabled = "true") and are used with that for a characters left item typically. Disabled elements can have their values changed by a script, but not by the user.

Another quick note: type="hidden" inputs generally share a similar usage to type="text", except that they have no disabled property since they aren't visible.





Input - type="checkbox"
Checkboxes are some of the most useful form items, then again, all of them are useful really. There's only three things that really need to be mentioned: the "checked" property, the "disabled" property, and the "click" function. checkbox.disabled works in the same way as it does with a type="text" element, so we'll skip right to the "checked" property.

checkbox.checked is a boolean value and you can use it to either change whether or not the checkbox is checked or you can use it to check if the box is checked. Those are the basic uses. You never need to use the "value" property of a checkbox, because it returns "1" whether it is checked or not.

checkbox.click() is the last useful function of a checkbox. What it does is act as if the user clicked on the checkbox. Assuming the box is enabled, it is the same as saying "checkbox.checked = !checkbox.checked" which would invert the value of it being checked. If the box is disabled, it does nothing.





Input - type="submit" - type="button" - type="reset"
Oh joy, the buttons of forms. At this point, I assume you know what each button does by itself. There's not much else to discuss on these buttons besides mentioning that they support the "disabled" property and that doing anything with their "value" property will update the text on the button. I'll give an example of a helpful function/event to use on your buttons in a script however.

<input type="submit" value="Submit" onclick="disable(this.form);" />
<script type="text/Javascript">
function disable(f){
  if(!f.nodeName || f.nodeName.toLowerCase() != "form"){ // Makes sure the element provided is a form.
      return false;
  }
  for(var a=0;a<f.elements.length;a++){
     if(f.elements[a].nodeName.toLowerCase() == "button" || (f.elements[a].nodeName.toLowerCase() == "input" && f.elements[a].type.match(/^(submit|reset|button)$/i))){
        // Disable elements if it's a button, or a input with type="submit", type="reset", or type="button"
        f.elements[a].disabled = true;
     }
  }
}
</script>


I will not break down this code, as you should be able to understand it just by having read this tutorial. I did however leave two comments to help you out.





Textareas
A textarea is one of the stranger form elements. Despite being setup without a value property in the HTML and making it look like innerHTML would return whatever is between the <textarea> and </textarea>, it doesn't. What is between those two tags is actually the value property. You can change this property, but it is recommended that you do not attempt to ever change the innerHTML of a textarea, unless you want to experience some weird changes to your webpage.

Also, textareas support the "disabled" method, which can come in handy.





Selects
Note that I'm not going to cover selects with multiple="multiple", just a basic select. To begin things off, selects support the disabled property. Also, for all examples, we'll be using the following select:

<select name="theSel" id="theSel">
  <option value="opt1">Option 1</option>
  <option value="opt2">Option 2</option>
  <option value="opt3">Option 3</option>
</select>


As you can see, we have three options within our select. If we were to alert the "length" property of our select, it'd return 3 since there's three options. We can also use this method to access the options. For example, document.testForm.theSel[0] would return a node reference to the first option. You can also access options through the "options" property, which happens to be an array.

Now, let's figure out how to get the value. Calling the "value" property on the select will return the value, and you can set the value this way too. But setting the value that way has problems. For example, if you attempt to set the value to something that doesn't have a corresponding option with that value, it won't update the select at all. This is where we're going to mention selectedIndex. selectedIndex is a property that contains a number corresponding to the placement of the currently selected option in the theSel.options array. So, theSel.options[theSel.selectedIndex].value is the same as theSel.value.

selectedIndex is most useful when having to reorder or remove items from a select. Say for example, you want to remove an item from a select once a user selects it. The code might look like this.

<select onchange="this.removeChild(this.options[this.selectedIndex]); this.selectedIndex=0;" name="theSel" id="theSel">
  <option value="opt1">Option 1</option>
  <option value="opt2">Option 2</option>
  <option value="opt3">Option 3</option>
</select>


That way when you remove the select, if you don't know the value of the first item, you can still set it to that item. This code itself would have problems since you couldn't select to remove the first item, but that's something we'll fix another day.

Now we're going to delve into adding, removing, and checking the selection on options. To add an option, it is easiest to use a simple DOM method.

<script type="text/Javascript">
var theSel = document.testForm.theSel; // Grab the select
theSel.appendChild(document.createElement("option")); // Create the option
theSel.lastChild.value = "opt4";  // Since we appended the option, it is the last child of the select.
theSel.lastChild.innerHTML = "Option 4"; // Set the innerHTML. Can also be referenced with "data"
</script>


Now we've created an option, we can also remove it.

<script type="text/Javascript">
var theSel = document.testForm.theSel; // Grab the select, again.
for(var a=0;a<theSel.length;a++){ // Loop through the options
  if(theSel[a].value == "opt4"){ // Check the value
     theSel.removeChild(theSel[a]); // Remove the child.
 break; // Found it. Break loop.
  }
}
</script>


That's a nice easy way to remove an option from the select. Now, let's try removing the option only if it's selected. I'll show two methods.

<script type="text/Javascript">
var theSel = document.testForm.theSel; // Grab the select, yet again.

// METHOD 1
for(var a=0;a<theSel.length;a++){ // Loop through the options
  if(theSel[a].selected == true){ // Check if selected
     theSel.removeChild(theSel[a]); // Remove the child.
 break; // Found it. Break loop.
  }
}

// METHOD 2
theSel.removeChild(theSel.options[theSel.selectedIndex]);
</script>


Both ways of removal work equally well. This concludes the select section.





Well, hopefully this tutorial helped some future coders out there to learn the basics of form manipulation. :P There's much more that can be done, but this will at least help you get a basic understanding and set you on your way to manipulating basic forms. If you need any help, feel free to post/comment.

newBookmarkLockedFalling