RSS
email

Creating Dynamic Div - Display error in form validation:



Sometimes we use alert user about wrong information supplied .. instead of using alert we can display information in document itself..

here is the full code and code explanation follows..

<html>
<head>
<style type="text/css">
#error
{
margin:0 auto;
background-color:#FFFFCC;
border:#FF822F 1px solid;
}
</style>
<script language="javascript">
function fun()
{
if(document.getElementById('frm1').txt1.value=="")
{
var div_element=document.getElementById('error_full');
var str_error="<div id=\"error\">Enter Valid Name:</div>";
div_element.innerHTML=str_error;
}
else{
var div_element=document.getElementById('error_full');
var str_error="<div id=\"error\">Hi "+document.getElementById('frm1').txt1.value+" !!</div>";
div_element.innerHTML=str_error;

}
}
</script>
</head>
<body>
<div id="error_full"></div>
<form action="" id="frm1">
<input type="text" name="txt1"/>
<input type="button" value="Hello world!" onclick="fun();"/>
</form>
</body>
</html>


Code explanation

Style:
Styles can be applied using id or class, use #infront of style if we use id...and .(dot) if we use class.
Here we use id.
We supplied background color, boder information in style sheet..
<style type="text/css">

#error
{
margin:0 auto;
background-color:#FFFFCC;
border:#FF822F 1px solid;
}
</style>

HTML:
DIV with id error_full is where we create dynamic div
Form tag with textfield and button.
Button calls javascript function fun onclick..

<body>
<div id="error_full"></div>
<form action="" id="frm1">
<input type="text" name="txt1"/>
<input type="button" value="Hello world!" onclick="fun();"/>
</form>
</body>

Javascript:
getElementById('frm1') returns the element which has the id supplied as argument.
innerHTML=returns or writes the elements or text enclosed in the div

<script language="javascript">
function fun()
{
if(document.getElementById('frm1').txt1.value=="")
{
var div_element=document.getElementById('error_full');
var str_error="<div id=\"error\">Enter Valid Name:</div>";
div_element.innerHTML=str_error;
}
else{
var div_element=document.getElementById('error_full');
var str_error="<div id=\"error\">Hi "+document.getElementById('frm1').txt1.value+" !!</div>";
div_element.innerHTML=str_error;

}
}
</script>

Bookmark and Share

1 comments:

Anonymous said...

hi
i am a aatif This is a good site
by

 

Recent Posts

Recent Visitors

Donate Me

About Me

My photo
Chennai, Tamil nadu, India
Nothing more to say about me.. Just a Action Script programmer / Flex developer having 4.5 years of experience.