jQuery: appended table row doesn't contain CSS styling - javascript

I have a dynamically created table via jQuery, but when a row element is added via ajax request, the newly added row does not follow the CSS styling. Is there a way to fix this?
Below is an example of what I have:
function createTable(data) {
var row = $('<tr id=' + data.id + '/>');
$("#table").append(row);
row.append($('<td>' + data.name + '</td>'));
row.append($('<td>' + data.age + '</td>'));
}

Have you tried the following:
var table=document.getElementByI("table");
var row=table.insertRow(table.rows.length);
var cell=row.insertCell(row.cells.length);
$(cell).text(data.name);
cell=row.insertCell(row.cells.length);
$(cell).text(data.age);

Related

How to get table row specific column to be clicked using javascript?

I have given row a class name , and i want to set a click function to be clicked on specific column of that row.
Here is the code-
var row = $('<tr class="parent_row"><td>' + '</td>' + '<td>' + data1 + '</td>' + '<td>'
+ data2 + '</td>; + '<td>' + data3 + "</td></tr>"
My click functon-
$('.parent_row).find("td:eq(1)").(click(function(e) { })
This is not working, I want that second column of row that is 'data1' should be clicked. I need help?
You can rewrite like this :
$('.parent_row').find("td:eq(1)").on("click",function(e){
//your stuff
})
I tried it out and it worked for me in this way.
You should write click event on td.
$('tr.parent_row td:eq(1)').on('click', function(){
// handle it here $(this)
});

Create clickable row of a js populated table

I've created a table using an AJAX request to the database of items in our inventory displaying a picture/part name/price/stock remaining. When the table displays I would like to be able to click on any part of one of the rows and have it link to the item page associated with that item but it won't work.
I've tried the on.click with a static table written right into the html and it worked fine. Also if I direct the on.click script to just the table id instead of the table id and tr i can make the entire table clickable to the first row's href. So it appears that since the tr doesn't really exist in the html the javascript won't find it. Is there a way to get the script to recognize each 's href attribute?
HTML CODE + on.click script:
<html>
<body>
<table id="ctable">
<tbody id="tbody1" class="tbody1">
</tbody>
</table>
<script>
$('#ctable tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
</script>
</body>
</html>
.JS File CODE that creates table from .php file/mysql database
document.addEventListener('DOMContentLoaded', function() {
$.post('test.php', function(data) {
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "<tr>" +
"<td class=\"image\">" + '<img src="images/thumbs/' +
value.image + '">' + "</td>" +
"<td>" + '<a href="' + value.link + '">' + value.part + "
</td>" +
"<td>" + value.price + "</td>"
"<td>" + value.stock + "</td>"
"</tr>";
$('#tbody1').append(eachrow);
});
});
}, false);
If you are dynamically adding rows, you need to either restructure your click event to listen from the context of the parent as in:
$("#tbody1").on("click", "tr", function(e) {
});
Assuming #tbody1 is a good place to start since you probably don't want the header row to be clickable. Or, every time you dynamically add rows, since the code is rebuilding the table, you can reattach the click event handlers:
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "..
$('#tbody1').append(eachrow);
});
// or .on("click", function() { })
$("#tbody1 tr").click(function() { });
If you attach click handler via on, it would be good to then do an off as in:
$("#tbody1").off("click", "tr");
To remove the existing click handlers.

How to create img tag string in javascript

I am trying to create image tag string in javascript. This image tag in part of table row string. At the end I will append this table row string to mvc webgrid using jquery.
I have a javascript function which returns this new row
function getNewRow(email, friendlyName) {
var imgSrc = "/Content/Images/User.png";
// Create the new row html
var newRow = '<tr class=\"' + rowClass + '\">' +
'<td><text><img src\"' + imgSrc + '\"></text></td>' +
'<td>' + email + '</td>' +
'<td>' + friendlyName + '</td>' +
'</tr>'
return newRow;
}
I will append returned string to webgrid object.
// Append the new Row
$('#group').append(newRow);
But the image tag is not showing proper image. The forward slash is removed after appending. Used encodeURIComponent function but no use.
How to make it to show the image properly.
You have <img src\"' + imgSrc + '\"></text></td> when it should be <img src=\"' + imgSrc + '\"></text></td>. Notice the missing =.
It seems that you have a typo in the second line of newRow declaration, you are missing the = sign after src attribute

hide a table td using Jquery

In the following code how can i hide the id column of the table.
var joblist = "";
joblist = joblist + "<table ><tr><th >Select</th><th id='td_1'>ID</th><th >Name</th><th >Names</th><th>OS</th><th >Server</th></tr>";
var tabString = '<tr ><td > ' + '<input type="radio" name="joblist" onclick="myfunc(this);" id= ' + value.jobid + 'value=' + value.jobid + '> </td><td id="td_1" >' + value._id + '</td><td >' + value.names + '</td><td a>' + value.os + '</td><td >' + value.server + '</td></tr>';
joblist = joblist + tabString;
I tried
$("#td_1").hide()
But it is not working.Any other solutions?
First of all if there is multiple td then don't use same id, in this case add some other post or pre. And use as
$('[id^="td_1"]').hide();//for post
$('[id$="td_1"]').hide();//pre
Try this
$('[id="td_1"]').hide();
First of all ID must be unique. you have declared same ID for TH and TD
$("#your_td_id").hide();
if you more than one TD then use class instead of ID.
As others have mentioned, you cannot match multiple elements based purely on an ID; they must be unique across the entire document. I suspect that what you are seeing is the 'ID' heading disappearing from the top of your table, but the values remaining visible later on in the table.
Other answers have mentioned switching to a class; there is another alternative available, using the nth-child pseudo-selector:
$("table tr > *:nth-child(2)").hide();
This will hide the 2nd element immediately under tr, as * matches both the TH and the TD. If you never want it visible, then better solutions include CSS:
table tr > *:nth-child(2) { display: none; }
or simply rendering it into an <input type='hidden' /> instead and including it in one of your existing cells (e.g. alongside the radio button).
Note that you have a few additional errors in your HTML, including:
<td a>' + value.os +
that you may want to investigate at the same time.
Before hiding an element you must assign it to DOM. If you want to hide multiple elements you must use class attribute instead of id
var joblist = "";
joblist = joblist + "<table ><tr><th >Select</th><th class='td_1'>ID</th>" +
"<th >Name</th><th >Names</th><th>OS</th><th >Server</th></tr>";
var tabString = '<tr ><td > ' + '<input type="radio" name="joblist"
onclick="myfunc(this);" id= ' + value.jobid + 'value=' +
value.jobid + '> </td><td class="td_1" >' + value._id +
'</td><td >'+ value.names + '</td><td a>' + value.os +
'</td><td >' + value.server + '</td></tr>';
joblist = joblist + tabString;
$('#myElement').append(joblist);
$('.td_1').hide();

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources