Friday, 26 October 2007

Ajax: add a new element into a list using javascript insertBefore()

This tutorial is a very simple javascript function that add an element <li> into a list <ul> without reload the page. The element is passed from a input text field and is added on top of the list using insertBefore() javascript function.

Download this tutorial


Step 1: HTML code
First, we prepare the HTML code for our page:
  • <input> text field (with id="newElement") for add new element.
  • <ul id="myList"> the list into we will add new elements.
  • <div id="msg"></div> a layer that will show a message if the add action has been completed, or an error if the input field is emty.
Copy and paste this code into the <body> tag:

<style>
body{font-family:'Lucida Grande', Verdana, sans-serif; font-size:14px; color:#666666;}
a:link, a:visited{color:#0033CC;}
h3{border-bottom: solid 2px #DEDEDE; padding:6px 0; color:#000000;}
#msg{background:#FFFFCC; margin:10px; padding:4px; display:none;}
</style>

<h3>Add a new element into a <ul> list</h3>
Add a new element into the list (press "submit" button)<br><br>
<input name="newElement" id="newElement" type="text" value=""/>
<input type="button" value="submit" name="submit" onClick = "javascript:addElement()"/>

<div id="msg"></div>

<ul id="myList">
</ul>


Step 2: the javascript function addElement()
This is the javascript function that use insertBefore() to add the new element on top of the list.In the previous code, to te step 1, add this <script> between <h3>Add a new element into a <ul> list</h3> ... and ... </style> line.

<script language="javascript">
function addElement(){
// Get the value into the input text field
var element=document.getElementById('newElement').value;
if(element==""){
// Show an error message if the field is blank;
document.getElementById('msg').style.display="block";
document.getElementById('msg').innerHTML = "Error! Insert a description for the element";
}else{
// This is the <ul id="myList"> element that will contains the new elements
var container = document.getElementById('myList');
// Create a new <li> element for to insert inside <ul id="myList">
var new_element = document.createElement('li');
new_element.innerHTML = element;
container.insertBefore(new_element, container.firstChild);
// Show a message if the element has been added;
document.getElementById('msg').style.display="block";
document.getElementById('msg').innerHTML = "Elemend added!";
// Clean input field
document..getElementById('newElement').value="";
}
}
</script>


Save and try it!

No comments:

Post a Comment