Sunday, February 20, 2011

Building dynamic html with Jquery

While reviewing the jquery code for a project developed at syneity. I came across the following javascript where dynamic html was handcoded and then applied to a table, we had encountered several such situations and it was a buggy experience. This blog details the refactoring i made to the same.

The problem:

image


 

This javascript was responsible for adding a new row to a table along with the input elements with their correct names.

Analysis:

The options for making the script more readable and maintainable were:

  1. Make dom elements on the fly by passing html strings to jquery.
  2. Use microsoft template.

Todays Solution:

The second option is an excellent one and one that we use frequently, however we will use the first option of using jquery to build the dom elements on the fly.

Simple POC

We will first try out the concept by adding an input text to a div and assign it the proper id and name.

image

 


Now the above script adds an input with the name “test-name” to the div.

How does this work?

The statement

$(“<input/>”).attr(‘name’, ‘test-name’).appendTo(“#simple-poc-div”);

can be broken down into three parts :

  1. $(“<input/>”) –> this creates a jquery object with the html passed in.
  2. .attr(‘name’, ‘test-name’) –> the jquery object is assigned the name attribute
  3. .appendTo(“#simple-poc-div”); –> the jquery object is appended to the div

The final implementation:

 function getNewRow(step) {
var tblRow = $("<tr>");
var tblData = $("<td>");
var inputText = $("<input>").clone()
.attr('type', 'text');
var row_id = parseInt($('#tbl >tbody >tr').length);
var suffixName = "." + row_id;

var inputName = inputText.clone()
.attr('name', 'name' + suffixName);
var inputAge = inputText.clone()
.attr('name', 'age' + suffixName);

tblRow.clone()
.append(tblData.clone().append(inputName))
.append(tblData.clone().append(inputAge))
.appendTo('#tbl > tbody:last');
}




The problem and refactored code is available in the download

No comments:

Post a Comment