JavaScript Create Element – Part 1

This is a simple tutorial helps you start with how to create html elements dynamically using createElement functionality.

XHTML Code

	<h1>JavaScript Create Element</h1>
	<h2>All the tags created dynamically will be added to "subMain" div.</h2>
	<div id="main">
		<form action="#" id="cEleForm" method="post">
			<label><strong>Enter a Tag:</strong><em>(Example:a, p, div, span...)</em></label>
			<input type="text" id="textBox" />
			<input type="button" value="Create" onclick="createEle()" />
			<input type="button" value="Clear Status" onclick="clrSts()" />
		</form>
		<div id="msg"> </div>
	</div>

	<div id="subMain"> </div>

Below is the JavaScript that uses document.createElement functionality to create html elements dynamically:

JavaScript

	function createEle () {
		var sm = document.getElementById('subMain');
		var sMsg = document.getElementById('msg');
		clrSts();
		if(sm) {
			sm.innerHTML +=	"";
			var getTag = document.getElementById('textBox').value;
			if (getTag != '')
			{
				var addNewTag = document.createElement(getTag);
				sm.appendChild(addNewTag);
				sMsg.innerHTML += "Status: "+getTag+" tag added Successfully!... Please check view source."; document.getElementById('textBox').value = ""; } else {alert ("Please enter a tag");} } }

Here is a bit of explanation on how this works:

Prerequisites: You should already be familiar with XHTML before reading further.

The JavaScript createElement and appendChild are the key functions which helps us to create html elements dynamically.

Let’s examine the below code:

document.createElement('p')

The createElement function takes html tag as parameter and creates the tag dynamically. Once the element is created it have to be added to the DOM to access it using appendChild function. Have a look at the below code:

sourceNode.appendChild()

The below example shows how to create a tag dynamically and add it to the “subMain” div.

var sm = document.getElementById('subMain');
var addNewTag = document.createElement('p');
sm.appendChild(addNewTag);

Few things to consider carefully: All the elements which are added dynamically will always be added at the end(In my example the p tag will be added as the last tag in div subMain). Withiout appendChild you will not be able to see the tag anywhere. The dynamically created tags are always empty.

Click here to download the complete code.

Good Luck!

Simple Form Validation using jQuery

In this tutorial I will cover a lightweight form validation from scratch. It is not advanced and powerful as the official plug-in. But you will get an idea on how simple it is to use jQuery to validate a form.

Prerequisites: You should be familiar with XHTML, CSS and little bit of JavaScript and jQuery before reading further. I would recommend you to go through this tutorial on jQuery to have a better understanding on few basics.

XHTML form

The mark-up is simple. I’ve not added any complex properties for any tags. I’ve tried to use the form elements that are mostly used on web.

	<form method="post" action="#nosend.php" id="basicFormVal">

		<label for="Name">Name:</label>
		<input type="text" id="name" name="name"/>

		<label for="Name">Gender:</label>
		<p><input type="radio" id="male" name="gender" /><span>Male</span></p>
		<p><input type="radio" id="female" name="gender" /><span>Female</span></p>
		<div class="clear"> </div>

		<label for="Phone">Phone:</label>
		<input type="text" id="phone" name="phone"/>

		<label for="E-Mail">E-Mail:</label>
		<input type="text" id="email" name="email"/>

		<label for="Country">Country:</label>
		<select id="country">
			<option selected="selected">Please Select your Country</option>
			<option value="DZ">Algeria</option>
			<option value="ZW">Zimbabwe</option>
		</select>

		<label for="Feedback">Feedback:</label>
		<textarea id="feedback" rows="6" cols="40"></textarea>
		<div class="clear"> </div>

		<p class="s"><input type="checkbox" id="signup" name="newsletters" />
		<label for="newsletters">Sign-up for our Newsletters:</label>
		</p>
		<div class="clear"> </div>

		<p class="formButtons">
			<input type="submit" value="Submit" id="submitBtn" />
			<input type="reset" value="Reset" id="resetBtn" />
		</p>

	</form>

jQuery

Here is the bit of jQuery I’ve used to do a simple validation on the above form.

	$(function(){
		$('#basicFormVal').submit(function() {

			if ($('#name').val() == "" || $('#phone').val() == "" ||
				$('#email').val() == "" || $('#feedback').val() == "" ||
				$("#country").prop("selectedIndex") == 0 || $("#signup").prop("checked") == false || $("input[name*='gender']").prop("checked") == false)
				{
					alert('All the fields needs to be filled');
					var flagit = false;
				}
				else { var flagit = true;}

			return flagit;
		});
	});

Let’s have a look at how the code is transformed form JavaScript to jQuery. If I have to read the form in the XHTML using JavaScript I would use the following code:

var myForm = document.getElementById("basicFormVal");

Here is how it is written in jQuery:

$('#basicFormVal')

The $ is the shortcut to access jQuery. We can select any element using the tag name or id or class like we do in css. jQuery provides all the existing JavaScript properties, functionalities and also includes some additional useful features.

Let’s see some examples.

I have a div with an ID <div id=”myDiv”>Content</div>. Below is how I can use jQuery to select or read this div.

$('#myDiv')

I have a div with class <div class=”myDiv”>Content</div>. Below is how I can use jQuery to select / read this div.

$('.myDiv')

I simple have a div <div>Content</div>

$('div')

I’ve used similar selectors like above examples but here is a selector that might look a bit complex which is not. Let’s have a look:

$("input[name*='gender']")

If you see the XHTML form I’ve used a radio button group with name=”gender”. To access this radio button group I’ve used the above selector. The above code selects elements that have the specified attribute(name) with a value(gender). It might look confusing but it is very simple. Please go through the jQuery selectors to learn more about selectors and how to use them. They are very similar to the css selectors.

Let’s move on to the methods that I’ve used in this tutorial val() and prop(). These are general methods in jQuery that can be used to retrieve the values and properties of that element.

Here is a an example:
I have an input tag <input type=”text” id=”name” name=”name”/> and I want to alert the text entered into this field.

In JavaScript:
var myInp = document.getElementById("name");
alert(myInp.value);

In jQuery:
alert($('#name').val());

The val() method in jQuery is more powerful and can do lot more than just retrieving the values of the elements. Read all about it here: val()

Now the prop() method provides a way to explicitly retrieve property values like selectedIndex, tagName, nodeType, ownerDocument, defaultChecked, and defaultSelected. You can read more about it here: prop()

Please see the below code snippets to understand the two methods better:

To check the selected item index in the country list(As in XHTML form) I’ve the below:
$("#country").prop("selectedIndex") == 0

The below code is to verify if the check box is checked:
$("#signup").prop("checked") == false

Finally the submit() method is used to trigger the validation it’s similar to the method we have in JavaScript. Read more about it here:submit().

It is always good to learn basics even though we have plug-ins for everytihng 🙂

Click here to download the complete code.

Good Luck!

jsbin.com

JS Bin is a webapp specifically designed to help JavaScript and CSS folk test snippets of code, within some context, and debug the code collaboratively.

JS Bin allows you to edit and test JavaScript and HTML (reloading the URL also maintains the state of your code – new tabs doesn’t). Once you’re happy you can save, and send the URL to a peer for review or help. They can then make further changes saving anew if required.

Read more…

I’m using jsbin.com since a long time an excellent webapp to test bits of code in xhtml / css / javascript / jquery / json and more instantly.

Basic: Form Validation using JavaScript

This is a simple tutorial helps you start with form validation. In this tutorial we’ll build a simple XHTML form with JavaScript validation. You can then adapt this form to your own requirements.

XHTML Form

<form method="post" action="#nosend.php" onsubmit="return validate()" id="basicFormVal">
	<label for="Name">Name:</label>
	<input type="text" id="name" name="name"/>

	<label for="Phone">Phone:</label>
	<input type="text" id="phone" name="phone"/>

	<label for="E-Mail">E-Mail:</label>
	<input type="text" id="email" name="email"/>

	<label for="Country">Country:</label>
	<select id="country">
	        <option selected="selected">Please Select your Country</option>
		<option value="DZ">Algeria</option>
		<option value="AS">American Samoa</option>
		<option value="ZM">Zambia</option>
		<option value="ZW">Zimbabwe</option>
	</select>

	<label for="Feedback">Feedback:</label>
	<textarea id="feedback" rows="6" cols="40"></textarea>

	<input type="submit" value="Submit" id="submitBtn" />
	<input type="reset" value="Reset" id="resetBtn" />

	</form>


The below JavaScript checks if any fields are left empty. If the field is blank, an alert box alerts an error message, the function returns false, and the form will not be submitted:

JavaScript

function validate()
{
  var myForm  = document.getElementById("basicFormVal");
  if(myForm)
    {
      if (myForm.name.value == "" || myForm.phone.value == "" || myForm.email.value == "" || myForm.country.selectedIndex == 0 || myForm.feedback.value == "")
        {
          alert ("Please fill all the fields");
        }
        else
        {
          alert ("Good to submit");
          return true;
        }
    }
}

Here is a bit of explanation on how this works:

Prerequisites: You should already be familiar with XHTML before reading further.

The JavaScript function needs to be placed in the XHTML like below:

<form method="post" action="#nosend.php" onsubmit="return validate()" id="basicFormVal">

The function in the JavaScript is called when the form is submitted. JavaScript treats the XHTML as a tree structure which is called as Document Object Model(DOM). If you can picture this it will be much easier to understand how JavaScript works. Let’s examine the below:

var myForm = document.getElementById("basicFormVal");

The above statement is trying to find the element or the XHTML tag with an id “basicFormVal” with the help of document.getElementById(“basicFormVal”). Once it finds the tag it will store it in a variable myForm. Now myForm can be used as a reference point to read / manipulate the tags inside the <form> tag.

Let’s examine the next bits of code in the JavaScript

	
        myForm.name.value == ""
	myForm.phone.value == ""
	myForm.email.value == ""
	myForm.country.selectedIndex == 0 
	myForm.feedback.value == ""

Note: if you are not familiar with If…else or the conditional operators please go through these tutorials.

name, phone, email, country, feedback are the ids’ on the tags inside the <form> tag. Since we already have the <form> tag in myForm variable it is easy to reference / read the tags inside it using myForm.name which directly points me to the tag with id “name”.

Let’s examine myForm.name.value. The value here is the text object property (Read more about text object properties). Every tag have properties some common some are more specific to each tag. This property helps the JavaScript to read the value inputed by the user and finally checks it aganist empty charcter or null using ==”” and similarly does the same thing with all the specifed tags inside the form.

But when it comes to <select> tag the property is different as I’ve previously mentioned. Here the user cannot type anything he will have to choose form the options provided. So we don’t have the value property for <select> tag. All the options in the select tag are indexed starting from 0. This is the reason we check for selectedIndex == 0. If the index value is 0 it means that user didn’t select anything.

So the function checks all the conditions through if and returs true or false. When all the fields are filled it will return true and alows the form to submit or it will return false and alerts the user to re-fill all the fields.

Click here to download the complete code.

Good Luck!