Java Questions Java Questions - 7 months ago 82
Javascript Question

How do I create HTML table using jQuery dynamically?

I am trying to create a HTML table like the following dynamically using jQuery:

<table id='providersFormElementsTable'>
<td><input type="text" id="nickname" name="nickname"></td>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>

This is my actual table :

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>

This is the method which will create
elements taking

function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);

// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');

I also have a value which will be shown as tool tip.

Please help me to create a table dynamically with
tool tip and tr td

Thanks for the help...


I have almost done with the following code:

function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip

// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;

Here label is coming properly and the input box is not coming and it shows
[object Object]
where the text box has to come...

When I printed the
, I get the following:

[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]

What could be the issue?

Thanks to
who showed me path... :)


You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):


InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.


Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;