JavaScript form submit using image

Document Sample
JavaScript form submit using image Powered By Docstoc
					JavaScript form submit using image: example
The code:



<form name="myform" action="handle-data.php">
Search: <input type='text' name='query'>
<A href="javascript: submitform()"
><img src="go.gif" width="33" height="19" border="0"
></A>
</form>
<SCRIPT language="JavaScript1.2">
function submitform()
{
  if(document.myform.onsubmit())
  {
  document.myform.submit();
  }
}
</SCRIPT>


The form created by the code above:



Search:



How to use getElementById to get the elements in a form

There are many ways of accessing form elements, of which the easiest is by using the cross-browser
W3C DOM document.getElementById method. Before we learn more about this method, it would be
useful to know something about the Document Object Model (DOM), the concept of HTML nodes or
elements, and the concept of containers.

Each time you load an HTML page, the web browser generates an internal representation of the page
in the form of an inverted tree structure. Let us look at a simple form. We will use this form later to
demonstrate the use of the getElementById method.

<form name ="subscribe" id="subscribe_frm" action="#">

Your Name: <input type="text" name="name" id="txt_name">

Your Email: <input type="text" name="email" id="txt_email">

<input type="button" name="submit" value="Submit"
onclick="processFormData();">

</form>
In the above HTML form, each tag (such as <html>, <input> and <form>) is known as an element,
and a matching pair of opening and closing tags is known as a container (ex: <form> and </form>).
Each element can have attributes associated with it, such as:

<input type="text" name="name" id="txt_name">


Here, the <input> element has three attributes: type, name and id. What we are interested in, from
the perspective of being able to access this element from Javascript is the id attribute.


Accessing Form Elements using getElementById

In order to access the <input> form element, we can use the method of the document object
getElementById() like this:


var name_element = document.getElementById('txt_name');


The variable object name_element holds a reference to the input field in the above form called name
with the id attribute txt_name. Please note that this method can only be used to access elements with
a unique id attribute. Through this object we can access all of the properties of the <input> element
and even change the values of those properties.

To access the value of the above input field entered by a user, we use the following syntax:

var name = name_element.value;


In a similar way, it is possible to access the <form> element:

var frm_element = document.getElementById ('subscribe_frm');


Let us look at an example implementation of this method for accessing a form and all the user input
elements of the form.

As you can see from the demo, it is possible to toggle the visibility of the form itself. This is done by
accessing the form element <form> which we have seen above and setting its CSS display property
in this way:

var frm_element = document.getElementById('subscribe_frm');

var vis = frm_element.style;

if (vis.display=='' || vis.display=='none') {
vis.display = 'block';
} else {
vis.display = 'none';
}


If we put this code in a function each time the function is called, it would toggle the visibility of the
form.
Each of the three user input elements: name, email and mail_format can also be accessed by the
getElementById method in the same way. Simple input validation has been provided.


As an example, if you wanted to ensure that the name <input> field was not empty, we could use a
JavaScript regular expression for checking the user input: /^\s+|\s+$/g which would check for all
leading and trailing white spaces including tabs.

function trim (str) {
return str.replace (/^\s+|\s+$/g, '');
}


We could then use this function:

var name_element = document.getElementById ('txt_name');

if (trim(name_element.value) == '') {
alert ('Please enter your name');
}




Please enter your subscription information:


Your Name:


Your Email:


                 Plain Text
Mail Format:

Hide the form


The code

function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function checkEmail(email)
{

 var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

 if(pattern.test(email)) {
 return true;
 } else {
 return false;
 }
}

function toggleFormVisibility()
{
  var frm_element = document.getElementById('subscribe_frm');
  var sub_link_element = document.getElementById('sub');
  var nosub_link_element = document.getElementById('nosub');

    var vis = frm_element.style;

    if(vis.display=='' || vis.display=='none') {
      vis.display = 'block';
      sub_link_element.style.display='none';
      nosub_link_element.style.display='';
    } else {
      vis.display = 'none';
      sub_link_element.style.display='block';
      nosub_link_element.style.display='none';
    }

}

function processFormData()
{

    var name_element = document.getElementById('txt_name');
    var email_element = document.getElementById('txt_email');
    var mail_format_element = document.getElementById('slt_mail_format');

    var name = trim(name_element.value);
    var email = trim(email_element.value);
    var mail_format = mail_format_element.value;

    var error_message = 'The following fields had errors in them: \n\n';
    var data = 'You entered the following information: \n\n';

    var error_flag = false;

    if(name == '') {
      error_message += 'Name: Please enter your name\n';
      error_flag = true;
    } else {
      data += 'Name: ' + name + '\n';
    }
    if(!checkEmail(email)) {
      error_message += 'Email: Please enter a valid email address';
      error_flag = true;
    } else {
      data += 'Email: ' + email + '\n';
    }

    data += 'Mail Format: ' + mail_format;

    if(error_flag) {
      alert(error_message);
    } else {
      alert(data);
    }

}


Checking for getElementById support

We can check for the availability of the document.getElementById method using a conditional if
statement:

if (document.getElementById) {
// use this method
}


Please note that we only check for the method. We do not pass the id of the actual element that we
need to access. For instance, the code below would be invalid:

if (document.getElementById('txt_name') {
// use this method
}


The programs that we have seen so far work flawlessly in modern browsers that support the W3C
DOM implementation. All recent versions of Mozilla Firefox, Opera, Internet Explorer and Netscape
fall under this category. But if we had to support older browsers like Netscape 4 and Internet Explorer
4, we would have to use a different method to access form elements.

For Netscape 4, we would have to check for the availability of the document.layers property, and for
Internet Explorer 4, we would have to check for document.all

We could write a function that manages all this for us:

function getElement (id) {

if (document.getElementById) {
return document.getElementById(id);
}
else if (document.all) {
return window.document.all[id];
}

else if (document.layers) {
return window.document.layers[id];
}
}


Other Cross-browser ways of accessing form elements

There are two other cross-browser ways of accessing form elements:
document.getElementsByTagName and document.getElementsByName.


Using the document.getElementsByTagName Method

This method takes in as argument the name of a tag (element) and returns an array of all matching
tags (elements) found in the document.

In our form example, if we had to get a reference to all the <input> elements, we could use the
following code:

var inputs = document.getElementsByTagName('input');


The variable inputs is a reference to an array of all <input> elements including: <input
type="button">

				
DOCUMENT INFO
Shared By:
Stats:
views:1
posted:7/21/2013
language:English
pages:6
Description: JavaScript form submit using image