jquery - get the position number of clicked td in a table - javascript

<table>
<tr>
<td>me</td>
<td>you</td>
<td>we</td>
</tr>
</table>
Using Jquery i want to know which childrin was clicked and get the number of this childrin. like, if I click you, i want to get 2 and if we, then 3.. if me, then 1.
is there something like .nthchild(); in Jquery?
here is my fiddle to test: http://jsfiddle.net/vfp9x/

Simply use $(this).index(), you also have wrong id for table in live demo, it should be table1
Remember the index is zero based so you will get zero 0 for first element and 1 for second element and so on.
Live Demo
$('#table1').on('click', 'td', function () {
$('#out').text($(this).index()+1);
});
.index()
If no argument is passed to the .index() method, the return value is
an integer indicating the position of the first element within the
jQuery object relative to its sibling elements.

Try,
$('#table1').on('click','td',function(){
var child_number = $(this).closest('tr').find('td').index(this);
$('#out').text(child_number);
});
DEMO
Simply use .index() as per the other answer provider suggested, and also keep this way of getting the index also. it would helpful for you in some other contexts, like getting the index of the current element from a collection of elements (not siblings to each other)

Try Like
$("#ul").on('click', 'td', function () {
debugger;
alert(this.id);
});
Demo

Related

How to get last element in the .find() object by jquery

I have DOM like this:
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
...
When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.
I am using this method to get the last element,but it doesn't work.
$('.add-tr').click( function() {
var last = $(this).parent().find('.child:last').attr('data');
alert(last);
})
Any idea why? Or any other suggestion to get the last element in the table?
UPDATE
Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks
Try this
var last = $(this).parent().find('.child').find('tr').last().attr('data');
In your example you get last table, but you need get last tr
Example
'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.
As there is no data attribute on <table>, .attr('data') on it will return undefined.
To get the value of data attribute on last <tr> use the selector tr:last.
var value = $(this) // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute
As the .child element is next to the button, next() can be used to get the table.child element.
var value = $(this) // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of "data" attribute
I'll recommend to use data-* attribute to store data in custom attribute.
<tr data-num="0">Foo</tr>
<tr data-num="1">Bar</tr>
And to get the value of custom data attribute use data()
.data('num')
If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().
.index()
This will return index of an element. Note that this is zero-based index which is exactly how you want.
$(".parent").click(function(){
$(this + " tr:last-child").attr("data");
});
should do.
Your code was almost correct, you missed tr:last , i.e.:
var last = $(this).parent().find('.child tr:last').attr('data');
DEMO
http://jsfiddle.net/tuga/vr1knxqq/3/
$('.add-tr').click( function(event) {
var last = $(event.target).next().find("tr").last().attr("data");
alert(last);
})
fiddle-example
You can get an array of the tr elements by using find('.child tr')
and to get the last element in that array you can use last().
Putting it all together you have this:
$('.add-tr').click( function() {
var lastTr = $(this).parent().find('.child tr').last(),
lastData = $(lastTr).attr('data');
alert(lastData);
});
I have setup a codepen here http://codepen.io/anon/pen/aOzmKg to show this working.

Edit HTML Table Data cell using Jquery

I have an HTML table, and each cell of the table will have two data attributes. What I'm trying to do is set a button to switch the value being shown in the table between those two attributes.
<table class="table1">
<tbody>
<tr>
<td data-original="A" data-new="B"> A </td>
</tr>
</tbody>
</table>
I'm able to set new text and get attributes outside the table, but whenever I try to within the table I keep receiving an error:
'Uncaught -> TypeError: undefined is not a function'.
I've been receiving this error for a number of commands $('td').text(), .val(), .attr('td'), .getAttribute().
Am I missing a plugin or something for getting and setting values from tables?
ANSWER: I figured out the reason, I was an idiot and didn't mention that there would be numerous TD elements with repeating tags. I eventually used Underscore.js's each method to iterate through them and parts of the below answer to swap the values.
Just made a Fiddle:
$("button").on("click", function () {
$("td").text($.trim($("td").text()) == $("td").data("original")
? $("td").data("new") : $("td").data("original"));
});
to switch between the data-original and data-new values by checking the current text in the td and using a ternary operator.
By using trim() for the initial text issues in case of whitespace are taken care of (as I just noticed that you have whitespace in your example td).
Just in case the button isn't already in the DOM when the page is initially loaded, you have to adjust the on() to delegate the click event from a static parent element to the button, e.g. like this: $(document).on("click", "button", function () { ...
Instead of $(document) every other static parent element can be used.
And as you mentioned that the table will have multiple tds with data-attributes, I've just adjusted the Fiddle to take care of that:
$("button").on("click", function () {
$("td").each(function () {
$(this).text($.trim($(this).text()) == $(this).data("original") ?
$(this).data("new") : $(this).data("original"));
});
});
I don't know how .text() didn't work for you.
To set text inside td elements, you use .text(). To get the data inside data-current or data-new, jQuery has a handy function .data(tag), for example $(sel).data('current').
Here's a fiddle displaying usage of this on your problem.

jQuery remove tr with no results

I have a SQL-PHP printed table, and a select at the top of the table. The table contains contacts classified by towns.
At the beginning, the table shows all contacts. If I specify the town, I want to hide the rest.
I'm trying to use a jQuery script
<script>
function updateit(){
if ($("#table").filter("tr") === $("#selectTown").val()) $(this).show(););
else {$(this).hide();};
}
</script>
[...]
<select id="selectTown" onchange="updateit()"><option value="NY">New York</option><option value="TX">Texas</option></select>
<table id="table">
bla bla bla...
</table>
Before I tried with find() function, but with no success.
Any suggestions?
This line $("#table").filter("tr") === $("#selectTown").val() compares document elements to string, it would not work.
Simplest solution would be to do all elements hidden and than select and show all matching elements. Example:
$('tr').hide();
$('tr[value=' + $("#selectTown").val() + ']').show();
I'm not sure where you got the idea for this code, but filter() definitely doesn't do what you think it's doing. $("#table").filter("tr") is going to give you a list of tr elements in the table. That list itself isn't going to equal any selected value, it's just an array of elements.
Mocking up a few things in a jsFiddle here, perhaps you want something more like this:
$('#selectTown').change(function () {
$('#table tr').hide();
$('#table tr').filter(function () {
return $(this).find('td:first').text() === $('#selectTown').val();
}).show();
});
What this does is:
Bind to the change event of the select element (which is preferred over the inline binding you do in your markup, just in general).
Hide all of the tr elements first, you'll show the ones you want in a moment.
Show all of the tr elements which match the filter.
The filter in this case is a function which returns true if the text inside of the td element (you will likely need to update that selector) equals the selected value. The main difference here vs. what you tried is that .filter() is returning a list of matched (filtered) elements, not an actual value to compare. Internal to the filter is where the comparison takes place, in this case using a function (which needs to return true or false for any given element being filtered).

How to read attribute using jquery on input variable with variable selector?

I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).
the alert says tID is undefined.
javascript:
function (msg) {
var tID = $("table", msg).attr('id');
alert(tID);
$("#reloadme_"+tID).html(msg);
}
html:
<div id="reloadme_2036">
<table id="2036" class="customCSSclass">
...table contents...
</table>
</div>
Where have I gone wrong?
find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:
$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it
Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]
Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.
Maybe this is what you're looking for?
function reload(msg) {
var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
alert(tID); //alerts 2036
$("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');
If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.
Check out the JSFiddle.
You have to try like this
var msg='<table id="2036" class="customCSSclass"></table>';
alert($(msg).attr("id"));

remove parent container

I have a form with the fields inside table cells. On the last column of each line I have an image. When clicking that image I want to delete the parent <tr>. Before I tried to do it by generating a function passing as the argument the line number: onclick='delete_row(x, y)'. This is obviously not a good solution since I was deleting the row by its position. The function I'm calling has other 2 arguments since it deletes the row in the database too, so the second argument is the id in the database to delete. So basically I need a function that deletes the parent <tr> and that accept some other arguments too.
EDIT Thanks:
Thank you all guys, I tried almost all the solutions and all worked nice. I just decided for the Mike's Samuel one, it seemed the easiest :) Thanks again
To pass the grandparent of the current node use this.parentNode.parentNode:
<tr><td><img onclick="delete_row(this.parentNode.parentNode, ...)"></td></tr>
How about removing the closest <tr>? You would need to make accommodations for the selectors that are present in your code, but the general form looks like this:
$('img').click(function(){
$(this).closest('tr').remove();
});
You could easily use the HTML node method .removeChild() and traverse through the node's .parentNodes: (demo):
<td onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
Remove row
</td>
this.parentNode.parentNode will be the <table> or <tbody>, while this.parentNode is the parent container <tr>.
Update: rjz provided a neat function (demonstration):
window.removeClosestRow = function(node) {
while(node = node.parentNode) {
if (node.tagName.toUpperCase() == 'TR') {
node.parentNode.removeChild(node);
break;
}
}
}
try something like
onClick='MyDeleteFunc(this, var2, var3)';
that will pass the actual object you're clicking on to javascript, and you can get pretty much all your references from there.

Categories