How do I create HTML table using jQuery dynamically? - javascript

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... :)

You may use two options:
createElement
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;
}

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);

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>

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.

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;
}

Related

Get value of first <td> element in same row as input button

I am trying to get the text from the first td tag from each row by using the input button as shown below:
for(var i in obj.questions){
question += '<tr class="row">';
question += "<td>"+ obj.questions[i].question+"</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
document.getElementById("t01").innerHTML = question;
}
The id=t01 is for the table tag. Here is the js that I tried working on but is not working:
var question;
$('.question').click(function() {
question = $(this).parent().find('td:first-child').text();
});
You have to iterate through each row like below
$('.question').click(function () {
$('#t01 .row').each(function () {
console.log($(this).find("td:first-child").text());
});
});
Also I would suggest to write html use jQuery instead of javascript instead of document.getElementById("t01").innerHTML
$('#t01').html(question);
Also your implementation of creating rows dynamically have one problem , you will get only one row every time. You can change your code like below
var question = "";
for (var i in questions) {
question += '<tr class="row">';
question += "<td>" + questions[i].question + "</td>";
question += '<td><input type="button" class="question" value="Add question" onclick="addQuestion()"></td>';
question += "</tr>";
}
$('#t01').html(question);
I have created a running sample for you
https://stackblitz.com/edit/jquery-n4spxc?file=index.js
You may need to use .live() to achieve this, depending on the order of your event binding and HTML generation. Also, consider revising your click event logic so that you iterate over all rows of the table to access the text of "first cell" for each table row:
// When the .question input is added to the DOM, this event logic will
// be bound to the input element automatically
$(document).live('.question', 'click', function() {
var question;
// Iterate over each row of the table
$('#t01 .row').forEach(function() {
// For each row, extract the text from first row cell
var row = $(this);
var firstCell = row.find('td:first-child');
var firstCellText = firstCell.text();
// Not sure how you want to use the data, this shows
// how to construct a comma separated string of text
// from all first row cells
question += firstCellText + ',';
});
// Print result to console
console.log(question);
});

How to check ajax data.d is null in append?

I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.
Am trying like this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
but it is not working please help me how to fix this...
Never understand why somebody use this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
Instead of this:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.
Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.
You could use something like this,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);
You could use :
if( data.d ){
//Your code
}
That will check if data.d is NULL or empty string "".
If you want to check in every iteration use the index i :
if( data.d[i] ){
//Your code
}
Hope this helps.
Take a look to https://stackoverflow.com/a/5515349/4281779.

How can I update the attributes of an HTML element inside a table cell?

I have a table which looks essentially like this
<!DOCTYPE html>
<html lang="en">
<body>
<table class="ui table" id="items">
<tbody>
<tr data-toggle="fieldset-entry">
<td><input id="items-0-quantity" name="items-0-quantity" type="text" value=""></td>
<td><input id="items-0-description" name="items-0-description" type="text" value=""></td>
</tr>
</body>
</html>
Using javascript, I'd like to have a button which adds a new row to the table, and I'd like the inputs in that new row to have id="items-1-xxx", and name="items-1-xxx, i.e. where there's a 0 in the original row I'd like a 1 in the new row.
I can make a new table row by cloning the old one, but I have not figured out how to modify the name and id attributes of the input.
Here's a sketch of what I've tried:
function cloneRow() {
var table = document.getElementById("items");
var original_row = table.rows[table.rows.length - 1];
var new_row = original_row.cloneNode(true);
// We have a new row and now we need to modify it as
// described in the question. The only way I've found
// is to grab the inner HTML:
var cell_contents = original_row.cells[0].innerHTML;
// Now we could do a bunch of string parsing and manipulations
// to increment the 0 to a 1 and stuff the modified HTML into
// new_row, but it seems there must be a better way.
// Finally insert the new row into the table.
original_row.parentNode.insertBefore(new_row, original_row.nextSibling);
}
What is the right way to update the input elements' id and name?
You could just build a new <td> and assign document.querySelectorAll('#items tr').length as the x in items-x-...:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length
, newitemQuantityText = 'items-' + itemcount + '-quantity'
, newitemDescriptionText = 'items-' + itemcount + '-description'
, newitem = document.createElement('tr')
, newitemQuantity = document.createElement('td')
, newitemDescription = document.createElement('td')
, newitemQuantityInput = document.createElement('input')
, newitemDescriptionInput = document.createElement('input');
newitemQuantityInput.id = newitemQuantityText;
newitemQuantityInput.name = newitemQuantityText;
newitemQuantity.appendChild(newitemQuantityInput);
newitemDescriptionInput.id = newitemDescriptionText;
newitemDescriptionInput.name = newitemDescriptionText;
newitemDescription.appendChild(newitemDescriptionInput);
newitem.appendChild(newitemQuantity);
newitem.appendChild(newitemDescription);
document.querySelector('#items').appendChild(newitem);
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items"></table>
However using good old innerHTML reads way better:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length;
items.innerHTML += '<tr><td>' +
'<input id="item-' + itemcount + '-quantity" name="item-' + itemcount + '-quantity">' +
'</td><td>' +
'<input id="item-' + itemcount + '-description" name="item-' + itemcount + '-description">' +
'</td></tr>';
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items">
</table>
You can separately reconstruct the node itself by using
createAttribute()
createElement()
Fiddle: http://jsfiddle.net/ztb9gq3d/1/
This is not the data oriented approach the question asks for, but a reasonably simple solution is
numRows = table.rows.length;
// Use a regexp so we can replace all instances of the number
// corresponding to what is currently the last table row.
var re = new RegExp((numRows - 1).toString(), "g")
for (var i = 0; i <= originalRow.cells.length - 1; i++) {
var originalHTML = originalRow.cells[i].innerHTML;
var newHTML = originalHTML.replace(re, numRows.toString());
newRow.cells[i].innerHTML = newHTML;
}
Obviously this only works if the number we replace doesn't exist elsewhere in the HTML string, so this is not a particularly good solution.
However, we could use a more complex regexp.
This solution does have the advantage that we don't need to hard-code anything except the parts we want to replace into the regexp.
Therefore, if the HTML in the table were to acquire additional parts in future development this solution will still work, up to the quality of the regexp as already mentioned.

How do I read dynamic data passed in an event handler in dynamic table

I am dynamically constructing table rows using jquery.
In the following chunk of code, how do I read someValue in method prepareDiv()?
$( document ).ready(function() {
var someValue = "DummyValue"
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td><a href="#" onclick="prepareDiv('+ someValue +');"><img src="../images/downarrow.jpg"></td></tr>';
$('#resTable tr').first().after(html);
});
function prepareDiv(value){
alert("value" + value);
}
I am using IE. Upon calling ready(), I get error DummyValue is undefined.
The problem is that you're ending up with generated code that looks like this:
onclick="prepareDiv(DummyValue);"
The lack of quotes around DummyValue means that it's expected to be a variable, whereas you want it to be treated as a string literal, so you need to add the quotes yourself:
onclick="prepareDiv(\''+ someValue +'\');"
That should result in:
onclick="prepareDiv('DummyValue');"
Just do something like this...the dynamically added values should be appended to tbody
var table = $("table tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
firstVal= $tds.eq(0).text(),
secVal = $tds.eq(1).text(),
thirdVal = $tds.eq(2).text();
alert(firstVal);//etc..
});
You have fews syntax errors, try this:
$( document ).ready(function() {
var someValue = "DummyValue";
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td>' + '<img src="../images/downarrow.jpg" /></td></tr>';
$('#resTable tr').first().after(html);
});

Is there any way to handle a particular column while adding the rows dynamically?

I am generating a dynamic table on click of a button as below -
$('.addRowButton').click(function () {
++counter;
var index=counter-1;
var newRowHtml =
'<tr>' +
'<td>' + counter +
'</td>' +
'<td><input name="b2bProductList[' + index+ '].productId" class="variant b2bTableInput" /></td>' +
'<td align="center"><span id="pvDetails" class="pvDetails"></span></td>' +
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
'<td><input name="b2bProductList[' + index + '].quantity" class="qty b2bTableInput"/></td>' +
'<td align="center"><span id="mrp" class="mrp"/></td>' +
'<td align="center"><input id="totalPrice" readonly="readonly" class="totalPrice b2bTableInput" type="text"></td>' +
'</tr>';
$('#poTable').append(newRowHtml);
But I want to handle a particular column my self - kind of override it. I have to display an image and have to use some attributes in this column it which I can not put in the above code. How should I override it. If I am going to declare any tr or td in my table in the main <table></table> they are taking up extra row statically. Is there any particular way to handle a particular column while adding the rows dynamically?
EDIT - I have to set the source of the image, the source string of which I am fetching through an async call on the focusout of my Id textbox. Now can not set the source in the row generation time, so I will have to handle each column at a time giving src after I have fetched it. The column is mentioned in my code
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
Now I have to set the src. I hope this tells my problem clearly.
You could use
$('#myTable tr td::nth-child('+columnIndex+')')
if you know the index of the column or you could give that specific td a unique class
newRowHtml ='<tr>' + '<td class="someClass"></td> ... etc
and select that class:
$('.someClass').each(function(){
// Some other code
});
Alternatively you could add the rows like so:
var $row = $('<tr></tr>');
var $id = $('<td></td>').html(id);
var $someOtherfield = $('<td></td>').html(someOtherData);
$('#myTable').append($row.append($id).append($someOtherfield));
then use the variable $someOtherfield to access it and work on it.
$someOtherfield.find('img').attr('src' , yourSource);
The simplest to select the cells of a specific column, if you have no fancy colspan, is to use :nth-child() :
$('#mytable td:nth-child('+columnIndex+')')
var tds= $('#poTable').find("td:first");
will give you the first column.
and to iterate over the elements
tds.each(function(index){
//do your stuff here..
});
hope this helps..

Categories

Resources