How do I get the value of td using hierarchy? - javascript

<tr>
<td>#</td>
<td>2009</td>
<td><a class="delete_this">Click</a></td>
</tr>
I want to use jquery and get the text of 2nd (second) "td" when clicking the anchor. I want the "td" in the same tr as the anchor...
How do I do this?
So far I have
$(document).ready(function(){
$(".delete_this').click(function(){
var myNUmber = $(this).parent()....///And this i should write the code to get the text for second td in tr where the anchor belongs to
})
})

Here's a few ways:
$(this).parent().siblings("td:eq(1)").text()
If your looking for the cell before you can do it this way:
$(this).parent().prev().text()

var myNUmber = $(this).parent().siblings().get(1).text();
Details are here

$('.delete_this').closest('tr').children(':eq(1)') .text();
1) Get the .delete_this A tag
2) Get the parent TR
3) Get the 2nd TD
4) Get the Text of the 2nd TD

Your better adding just 1 click event by using .live rather than adding multiple click handlers, if you had a large table this will impact performance (think 100 separate bound events).
Also remember to prefix class selectors with nodeName if you can (here you are sure all delete_this are anchors)
$('a.delete_this').live('click', function(){
var myNUmber = $(this).parent().siblings().get(1).text();
});

Related

How can I get a clicked table row's TBODY?

I have a table with a few rows in it. Each row has an onclick event that is supposed to check the ID of the tbody element. This is stored in a variable for later use in a function.
Right now I have this snippet of jQuery:
var parentTable = $(this.parentNode)[0].id;
However, this only gets the ID of the entire table, not the tbody.
What's the best way to specify the ID of the tbody element?
First, your use of jQuery is wasted there. It would be written like this:
var parentTable = this.parentNode.id;
As far as getting the tbody id, assuming this is actually the row, your code should do it.
If you're actually getting the table, then that would be very unusual. The only way a tbody would not get created would be if you manually created the table from DOM creation methods, and left it out.
You may want to store that information in a data-tbody-id for each row, then when the user clicks on the row, the event object will hold that information.
You can use the following function
var tobody = parentTable.children('tbody')
You can use the following function
var tbody = $(this).parents("tbody");
var id = tbody.attr("id");

Jquery - Setting value of <td>

I currently have a table and in 1 column a Delete link, if the user clicks this link it fires an onClick which basically flags that item to be deleted and hide the TR.
It works fine, but I am just wondering if there is a better way .....
$(document).on('click', '.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
var target = $(e.target);
if (!target.is('td')) {return;}
var h = this.innerHTML;
var newH = h.replace("CsUpdated", "CsDeleted");
newH = newH.replace("CsAdded", "CsDeleted");
this.innerHTML = newH;
//We clicked on a TD so get the row TR.
var theRow = $(this).closest('tr');
theRow.hide();
});
I just think there must be a better way than the string manipulation I am doing with the replace? Is there?
I've tried these but with no luck...
$(this).attr('value', 'CsDeleted');
$(target).attr('value', 'CsDeleted');
$(this).val('CsDeleted');
$(target).val('CsDeleted');
Thanks
td has no value use .text() or .html()
td doesnt have a value attribute.
Use
$("td").html() // to fetch html
$("td").html("<span> Hello World </span>") // to set html
$("td").text() // to fetch plain text
$("td").text("Hello World") // to set plain text
You could use any of the following to set the cell contents
.html() or .text() or .prependor .append and more
However .val() only works on inputs that have the value="...." attribute. If you want to prop the Cell with some data use .data("key","value") which can be accessed at any point by calling .data("key");
Try this one,
$(function(){
$('.delete').click(function(){
$(this).closest('tr').remove();
});
});
You may use custom data-- attributes on any html element ( see this MDN article and the reference ). These are accessible through jquery's attr method and have no influence on rendering.
Code PoC:
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this)
.removeAttr('data-CsUpdated')
.removeAttr('data-CsAdded')
.attr('CsDeleted', '1')
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
In case the values given in your code are mutually exclusive, this simplifies to
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this).attr('Cs', 'Deleted');
// attr 'Cs' contained 'Added' or 'Updated'
// This scheme requires modifications at other places in your original code !
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
Update
As the OP actually wants to modify the value of a child input element, the handler reduces to:
$(document).on('click', 'td.deleteCell', function (e) {
$('input', $(this)).val('CsDeleted');
// more specific selector may be needed depending on possible cell contents
$(this).closest('tr').hide();
});

How do you hide the first element in the first table?

I know that to hide the first element in a table is simply do (':first-child') but is there a way to specify that only the first element of the first TABLE needs to be removed?
In my situation the first element of every table is being hidden and I need to fix this.
I suppose you just target the first table, and then the first element, whatever that is ?
document.querySelector('table tr').style.display = 'none';
FIDDLE
as querySelector gets the first matching element, or in jQuery
$('table:first tr:first').hide()
FIDDLE
target the first table and the first td.
$('table:first td:first').hide()
DEMO
You can get a collection of all tables using document.getElementsByTagName("table"). Element zero of that collection ([0]) is the first table. You can then apply your first-child solution to element zero.
This does not require jQuery, nor that you assign an ID attribute to a specific table. (Assigning an ID attribute is probably more efficient if you know in advance which table is going to be first.)
Edited to add: I've tested this and it works, although it is revised from my first "it works" post. The first child element of TABLE is TBODY for a table that starts with a tr element, so what is really wanted is the first child of TBODY. It is probably better to descend the firstElementChild tree looking exspressly for a nodeName of "TR" and hide that. Look further down in this post for that approach.
Here is the simple code that works:
document.getElementsByTagName("table")[0].firstElementChild.firstElementChild.style.display = "none";
This is pure JavaScript, with no need for jQuery. Note that document.getElementsByTagName returns a live collection, so even if a table is added to the DOM, this will get the first one.
Do remember that the first element child of <table> (and then TBODY) is not necessarily <tr>. If you can be sure it is, or if you want the first element regardless, then what I've given will work for you. If you want to be sure it's a <tr> then a little more work will be needed.
This code finds and hides the first <tr> but will be less efficient because it gets two HTML collections:
document.getElementsByTagName("table")[0].getElementsByTagName("tr")[0].style.display = "none";
const tables = document.getElementsByTagName("table")
const firstTable = tables[0];
const firstRow = firstTable.rows[0];
firstRow.style.visibility = "hidden"; //hide
firstRow.style.visibility = "visible"; //visible
Here is a referrence.

Change text of specific <a> text using jQuery

I have an asp:Repeater that makes a table with a few <td>s and <tr>s. In each of the <tr>s, I have an <a></a>.
Now, on a certain event I want to change just the <a></a> tag in the <tr>.
So, I want to do something like:
$("a").text("I changed!");
, but I only want to change the <a>.text in one <tr>, not all the <a> elements on the page.
I am experimenting with .closest(), but unfortunately don't know enough about jQuery to make this functional.
if you have the target tr somehow, then you can use the following code to find the a tag inside that:
tr.find("a").text("text here");
How to find tr really depends on what context you are in and how your target tr is identified from others.
e.g. if it's the "first" tr you may say:
var tr = $("tr").first();
if it's the element that the event has happened for (e.g. click event):
var tr = $(this);
if you are in the event of a child element of target tr you may say:
var tr = $(this).closest("tr");
You should mark the <tr> with an Id so that you could identify it and then change the containing
So for example you could mark your <tr> with id 'myid' and do something like this in jquery:
$("#myid a").text("I changed!");
Or if you dont want to mark it with an Id then, you could use selectors if you know which it is.
For example getting the first would be:
$("tr:first a").text("I changed!");
Some references:
http://api.jquery.com/first-selector/
http://api.jquery.com/category/selectors/

jQuery remove range of rows

Let's say I have a table with these rows:
<table>
<tr id="before_dynamic_rows"></tr>
<tr id="after_dynamic_rows"></tr>
</table>
Using jQuery, I insert automatically generated rows (search results) before the after_dynamic_rows row. How can I delete a range of rows, namely - you guess it - the ones between the row with the id before_dynamic_rows and the row after_dynamic_rows? (In order to be able, after having inserted them, to remove them and insert different ones.)
var response = ajax.responseText;
$('#after_dynamic_rows').before(response);
That's how I insert the new rows. Considering the first answer: how can I assign a class to whatever the response text may be?
This answer is based on a literal interpretation of the question with the idea that the only rows which should be removed are those rows that are in between #before_dynamic_rows element and #after_dynamic_rows.
See working version at: http://jsfiddle.net/7wBzd/
var $rows = $("tr");
$("tr:lt("+ $rows.index($("#after_dynamic_rows")) +"):gt("+ $rows.index($("#before_dynamic_rows")) +")").remove();
$("table tr:gt(0)").not("#after_dynamic_rows").remove();
Try it out here.
Note if #after_dynamic_rows is the last row, then you can just do:
$("table tr:gt(0)").not(":last").remove();
or:
$("table tr:gt(0):not(:last)").remove();
...and if there are rows before #before_dynamic_rows, just do:
$("table tr:not(#before_dynamic_rows, #after_dynamic_rows)").remove();
I would assign a class to those added rows to make them easy to select, but you could select all tr children and use the 'not' method to remove the two you want to keep.
$("table tr").not("#before_dynamic_rows").not("#after_dynamic_rows").remove();

Categories