28

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

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

This is my actual table :

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

This is the method which will create tr and td elements taking id and labelText:

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.

EDIT:

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 textInputBox using console.log, I get the following:

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

What could be the issue?

Thanks to @theghostofc who showed me path... :)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Java Questions
  • 7,813
  • 41
  • 118
  • 176

5 Answers5

16

You may use two options:

  1. createElement
  2. InnerHTML

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

$(document.createElement('table'));

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.

Edit:

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;
}
Community
  • 1
  • 1
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
  • I tried this one, I don't get the title fully it escapes the given value, suppose if I have `Ex: My Home Connection` than I get only `Ex:` and rest are escaped. that is why did not use this one. :) Thanks for your time... – Java Questions Sep 17 '13 at 11:12
  • In that case you may try with some light-weight JQuery tooltip library – Vivek Jain Sep 17 '13 at 11:22
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/37516/discussion-between-theghostofc-and-anto) – Vivek Jain Sep 17 '13 at 11:26
  • 1
    Have you heard about Script injection? You need to HTML encode text values – Maksym Kozlenko Feb 16 '15 at 23:05
8

An example with a little less stringified html:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);
Luke W
  • 8,276
  • 5
  • 44
  • 36
2

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

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

Fabricio
  • 839
  • 9
  • 17
  • 1
    all values are dynamic not static as you have given in your answer. anyway thanks for the effort.` label and input name` etc are all dynamic . – Java Questions Sep 17 '13 at 10:17
2

I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .

Look at the code below :

HTML:

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

JS :

createFormElement("Nickname","nickname")

function createFormElement(labelText, id) {

$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}

This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .

WORKING DEMO:

Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.

It's much easier to construct just the html and change the id s of the label and input according to your needs.

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
2

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

GGSoft
  • 439
  • 6
  • 15