Legend tag in html with examples





  1. The <legend> tag is used for labelling the fieldset element. 
  2. By using the <fieldset> tag and the <legend> tag, you can make your forms much easier to understand for your users. 
  3. The <fieldset> tag is used to group the form elements while the <legend> tag provides a label for the fieldset. 
  4. The <legend> tag is supported in all major browsers.


Example :

     <html>
     <head>
     <title>Legend</title>
     </head>
     <body>
     <fieldset>
     <legend>Employee Information</legend>
     EmpId:<input type="text"><br/>
     Name :<input type="text">
     </fieldset>
     </body>
     </html>
     

Demo :



In the above example, we have shown how to use legend element with fieldset element. We have created a simple form having two fields. We have included the form in the fieldset element which gives it a better look. The legend element renders as label or header for fieldset element.



Legend and Style :



<html>
<head>
<title>LegendStyle</title>
<style type="text/css">
legend
{
background-color:lightblue;
color:blue;
font-size:30px;
font-family:comic sans ms;
border:2px dotted black;
}
</style>
</head>
<body>
<fieldset>
<legend>Employee Information</legend>
EmpId:<input type="text"><br/>
Name :<input type="text">
</fieldset>
</body>
</html>

Demo :




In the above example, we have rendered a fieldset and legend element. Using the element selector we have also applied CSS to the legend element.



Legend and Javascript :



<html>
<head><title>LegendJavascript</title>
<style type="text/css">
legend
{
background-color:lightblue;
color:blue;
font-size:30px;
font-family:comic sans ms;
border:2px dotted black;
}
</style>
<script type="text/javascript">
function legend()
{
var elementFieldset=document.createElement("fieldset");
var elementLegend=document.createElement("legend");
var textLegend=document.createTextNode("Employee Information");
elementLegend.appendChild(textLegend);
elementFieldset.appendChild(elementLegend);
var elementLabel=document.createElement("Label");
var textLabel=document.createTextNode("Name:");
elementLabel.appendChild(textLabel);
var elementTextbox=document.createElement("input");
elementTextbox.setAttribute("type","text");
elementFieldset.appendChild(elementLabel);
elementFieldset.appendChild(elementTextbox);
document.getElementById("legend").appendChild(elementFieldset);
}
</script>
</head>
<body>
<div id="legend">
</div>
<input type="button" id="b1" value="Press" onclick="legend()"/>
</body>
</html>
     

Demo :





In the above example, on button click, we created <legend> element, created a text node and appended to <legend> element, further we appended <legend> element to <fieldset> along with label and textbox element. And finally, we appended the fieldset element to <div> element. Thus on button click we have created a small form having fieldset, legend and one field in it using javascript.



0 comments:

Post a Comment