আগামী ১৫ ডিসেম্বর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ২৬ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

JavaScript Advanced Tutorial

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>

There are elements such as <input/> and containers like <form> </form> Each element can have attributes associated with it, such as:

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

ere, the <input/> element has three attributes: type, name and id. The idattribute uniquely identifies this particular element.

Accessing Form Elements using getElementById

In order to access the form element, we can use the method getElementById() like this:

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

The getElementById() call returns the input element object with ID ‘txt_name’ . Once we have the object, we can get the properties and call the methods of the object. For example, to get the value of the input element, get the value attribute.

</pre>
<div>
<div><code>var</code> <code>name = name_element.value;</code></div>
</div>
<pre>

Similarly, it is possible to access the <form> element:

</pre>
<div><code>var</code> <code>frm_element = document.getElementById (</code><code>'subscribe_frm'</code><code>);</code></div>
<div>

Example demo1.html: access and validation the form and input elements

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Demo: Using getElementById to get the elements in a form</title>
<script script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<a href="javascript:toggleFormVisibility();" id="sub">Subscribe to our Newsletter!</a>
<form name ="subscribe" id="subscribe_frm" action="#" style="display: none">
<div>
<p>Please enter your subscription information:</p>
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email"></p>
<p><label for="mail_format">Mail Format: <select name="mail_format" id="slt_mail_format">
<option value="TEXT">Plain Text</option>
<option value="HTML">HTML</option>
</select></p>
<p><input type="button" name="submit" value="submit" onclick="processFormData();" ></p>
</div>
<a href="javascript:toggleFormVisibility();" id="nosub" style="display: none">No, Thank you! Some other time, perhaps....</a>
</form>

Example demo1.js

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

function checkEmail(email)
{

var pattern=/^([a-zA-Z0-9_.-])[email protected]([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);
}

}

See the demo.
In this demo, we toggle the visibility of the form. This is done by accessing the form element <form> which we have seen above and setting its display property as shown in the code below:

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';
}

}

Input validation

The code below makes sure that the field is not empty.
First, we trim out any leading and trailing blank space.

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

The code below validates the txt_name field in our processFormData function.

var name_element = document.getElementById (‘txt_name’);</pre>
<div>
<div><code>if</code> <code>(trim(name_element.value) == </code><code>''</code><code>)</code></div>
<div><code>{</code></div>
<div><code>   </code><code>alert (</code><code>'Please enter your name'</code><code>);</code></div>
<div><code>}</code></div>
</div>
<pre>

Checking for getElementById support

All modern browsers support getElementById() method. However if you are to support very old browsers, use the following function:

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 element objects

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”>

Example Demo2.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Demo: Using getElementByTagNameto get the elements in a form</title>
<script script type="text/javascript" src="demo2.js"></script>
</head>
<body>

<form name ="subscribe" id="subscribe_frm" action="#">
<div>
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email"></p>
<p><label for="mail_format">Mail Format: <select name="mail_format" id="slt_mail_format">
<option value="TEXT">Plain Text</option>
<option value="HTML">HTML</option>
</select></p>
<p><input type="button" name="submit" value="submit" onclick="processFormData();" ></p>
</div>

</form>

Example demo2.js

What if we only wanted to access <input> elements with the type attribute as text? We could do it in the following way:

function processFormData()
{

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

var message = 'The form has the following input elements: \n\n';

for (var i = 0; i < inputs.length; i++) {
message += inputs[i].tagName + " element with 'type' attribute = '" + inputs[i].getAttribute('type') + "' and 'name' attribute = '" + inputs[i].getAttribute('name') + "'\n";
}

alert(message);

}

see the  demo

This time, the elements retrieved do not include the element: <input type=”button”>.

Example Demo3.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Demo: Using getElementsByTagName to get the elements in a form</title>
<script script type="text/javascript" src="demo3.js"></script>
</head>
<body>

<form name ="subscribe" id="subscribe_frm" action="#">
<div>
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email"></p>
<p><label for="mail_format">Mail Format: <select name="mail_format" id="slt_mail_format">
<option value="TEXT">Plain Text</option>
<option value="HTML">HTML</option>
</select></p>
<p><input type="button" name="submit" value="submit" onclick="processFormData();" ></p>
</div>

</form>

Example Demo3.js

function processFormData()
{

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

var message = "The form has the following input elements with the 'type' attribute = 'text': \n\n";

for (var i=0; i < inputs.length; i++) {
if (inputs[i].getAttribute('type') == 'text') {
message += inputs[i].tagName + " element with the 'name' attribute = '" + inputs[i].getAttribute('name') + "'\n";
}
}

alert(message);

}

see the demo

Using the document.getElementsByName Method

This method takes in as argument the name attribute value of elements to be retrieved and returns a collection of desired matching elements.

In the code snippet below, let us say we need to get a reference to the <select> element with the name attribute mail_format.

<div class="container">
<div class="line number1 index0 alt2"><code class="xml plain"><</code><code class="xml keyword">select</code> <code class="xml color1">name</code><code class="xml plain">=</code><code class="xml string">"mail_format"</code> <code class="xml color1">id</code><code class="xml plain">=</code><code class="xml string">"slt_mail_format"</code><code class="xml plain">></code></div>
<div class="line number2 index1 alt1"><code class="xml plain"><</code><code class="xml keyword">option</code> <code class="xml color1">value</code><code class="xml plain">=</code><code class="xml string">"TEXT"</code><code class="xml plain">>Plain Text</</code><code class="xml keyword">option</code><code class="xml plain">></code></div>
<div class="line number3 index2 alt2"><code class="xml plain"><</code><code class="xml keyword">option</code> <code class="xml color1">value</code><code class="xml plain">=</code><code class="xml string">"HTML"</code><code class="xml plain">>HTML</</code><code class="xml keyword">option</code><code class="xml plain">></code></div>
<div class="line number4 index3 alt1"><code class="xml plain"></</code><code class="xml keyword">select</code><code class="xml plain">></code></div>
</div>
&nbsp;

We could access the desired element in this way:

<div class="container">
<div class="line number1 index0 alt2"><code class="jscript keyword">var</code> <code class="jscript plain">mail_format_elements = document.getElementsByName(</code><code class="jscript string">'mail_format'</code><code class="jscript plain">);</code></div>
</div>

See All Code below:

demo4.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Demo: Using getElementByName to get the elements in a form</title>
<script script type="text/javascript" src="demo4.js"></script>
</head>
<body>

<form name ="subscribe" id="subscribe_frm" action="#">
<div>
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email"></p>
<p><label for="mail_format">Mail Format: <select name="mail_format" id="slt_mail_format">
<option value="TEXT">Plain Text</option>
<option value="HTML">HTML</option>
</select></p>
<p><input type="button" name="submit1" value="Elements with name='mail_format' attribute" onclick="processFormData('mail_format');" ></p>
<p><input type="button" name="submit2" value="Elements with name='email' attribute" onclick="processFormData('email');" ></p>
</div>

</form>

And demo4.js

function processFormData(name_attr)
{

var mail_format_elements = document.getElementsByName(name_attr);

var message = "The form has the following elements with the 'name' attribute = '" + name_attr + "': \n\n";

for (i=0; i<mail_format_elements.length; i++) {
message += mail_format_elements[i].tagName + ' element with "id" attribute = "' + mail_format_elements[i].getAttribute("id") + '"\n';
}

alert(message);

}


See Demo

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

One comment on “JavaScript Advanced Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *