javascript Clone

Using  javascript can make html clone on run time. Here we will see how to fomr a clone in the <table>’s  attributes <tr> and <td>values.

While making clone on the table attribute, here some html tag also present for the neatful presentation.

Create a table with id=”mainTbl”  as seen below with the simple html elements,

<table width=”100″ border=”0″ cellspacing=”0″ cellpadding=”2″ id=”mainTbl”>
             <tr>
               <td><select name=”reminder”>
                            <option value=”email” selected>Email</option>
                           </select> 
            </td>
                  <td>
                    <img src=”images/add.png” onclick=”insertRow();” /></td>
             </tr>
           </table>

Here onlick Add images as seen in the code we are calling insertRow() function to create clone as ,

function insertRow(){
    var tbl = document.getElementById(‘mainTbl’);   
     var lastRow = tbl.rows.length ;
    // if there’s no header row in the table, then iteration = lastRow + 1   
   var tr =document.createElement(“tr”);
   var td1 =document.createElement(“td”);
   var td2 = document.createElement(“td”);
   var td3 = document.createElement(“td”);

   td1.innerHTML = ‘<select name=”reminder”><option value=”email” selected>Email</option><option value=”sms”>SMS</option><option value=”alert”>Pop-Up</option></select>’;
   td2.innerHTML = ‘<input name=”min_value” type=”text” />’;
   td3.innerHTML = ‘<img src=”images/1244107465_time_delete.png” onclick=”removeRow();” />’;
   tr.appendChild(td1);
   tr.appendChild(td2);
   tr.appendChild(td3);   
 
   document.getElementById(“mainTbl”).getElementsByTagName(“tbody”)[0].appendChild(tr);
  }

Here createElement() creates the clone of <tr> and <td>. All the table elements HTML contents are get added using the appendChild() function as seen above.

By Runtime clone creation, we are creating delete event also for deleting the created clones using the removeRow(). This function will fire on click of  delete icon.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: