Resetting forms using an Image Button - With working DHTML Codes

Started by Kalyan, Oct 25, 2008, 11:53 AM

Previous topic - Next topic

Kalyan

Resetting forms using an Image Button

In forms when using text boxes or text areas and check boxes you might need a reset button that is not the usual gray HTML button. For this you can use an image field and a small JavaScript function as given below.

Note: This button will reset only text boxes,text areas and check boxes as list boxes and option buttons don't usually require resetting. After resetting the form the cursor will set the focus to the first field in the form.


JavaScript Code

<script  language = "Javascript">

function ResetForm(which){
var pass=true
var first=-1
if (document.images){
for (i=0;i<which.length;i++){
var tempobj=which.elements[i]
if (tempobj.type=="text"){
  eval(tempobj.value="")
  if (first==-1) {first=i}
}
else if (tempobj.type=="checkbox") {
  eval(tempobj.checked=0)
  if (first==-1) {first=i}
}
else if (tempobj.col!="") {
  eval(tempobj.value="")
  if (first==-1) {first=i}
}
}
}
which.elements[first].focus()
return false
}
</script>


Cut and paste the below code and then create your other fields inside the already created form. For the reset button in the given code just change the path to your image button.

HTML Code

<form onSubmit="return ResetForm(this)" method="post" action="#" name="">

<!-- place all your other fields here -->

<input type="image" border="0" name="imgReset" src="/images/reset.gif" width="62" height="20">
</form>


Explanation

There is just one JavaScript function ResetForm. The logic behind the functioning of this code is very simple.

    * The JavaScript first checks each element in the form submitted to see if it is a text field, text area or check box by checking the type property for a 'text field or checkbox' and checking the col property (no. of columns) for a 'text area' field. If found we set the field's value to null (for text boxes or text areas) or unchecked (for check boxes).

    * After resetting all values found it sets the focus to the first text, text area or checkbox field in the form. This is done by getting the index of the first form element encountered which was a text field, text area or check box and storing it in a variable called first. This variable is then used to set the focus.