As per trying to run in jsfiddle, I figured this should work, but it is instead returning blanks.
This is the example HTML
<table id = "test">
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
</table>
And I'm just trying to run this code against it.
var x = $( "#test").children("tr");
console.log(x);
But it is instead returning with nothing in x, rather than all of the tr elements.
Any ideas?
My ultimate goal is to create a function that will iterate through every tr and td in a selected table with jquery, allowing me to "set" div values into them for an online board game. Is this the best way?
The problem is that
$("#test").children("tr");
is equivalent to
$("#test > tr");
but most browsers insert a sorrounding tbody if there is none in the table, so #test > tr does not match any element, so it is better to use
$("#test tr");
or if you prefer
$("#test").find("tr");
use this:
var x = $( "#test").find("tr");
console.log(x);
You can try using .each()
Fiddle
$("#test td").each(function () {
var x = $(this).text();
console.log(x);
});
Related
My table is like this:
<table>
<tr>
<td>
<img src="" />
<span>blah</span>
</td>
</tr>
...
So in each row, first column contains an image. I need to register event on each of this image. So how can I select it?
I tried this:
td:eq(0):nth-child(0)
But it is not working.
something like this selector:
td:first-child > img
should work i guess...
For nth-child selector, the index is 1 based. I think something like this would work for you:
$("td:nth-child(1) > img")
or even simpler:
$("td:first-child > img")
I'd suggest:
$('table tr td:first-child img').on('event', function (){
// handle the event here
});
I think http://forum.jquery.com/topic/jquery-how-to-select-all-first-tds-inside-all-tr-in-a-table contains several solutions:
$('tr td:first-child')
$('tr').find('td:eq(0)')
$("tr td:nth-child(1)")
You can select the first column image of the table as follows :
$('tr').find('td:eq(0)')
$('table > tr > td:first-child > img').bind('click', function() {
// your code
});
I would give the table a unique id for more precision.
$('#table_id > tr > td:first-child > img').bind('click', function() {
// your code
});
Replace 'click' in the code above with wathever event you need to check.
Check this
$(function(){
$("table tr td:first-child").on("click","img",function(){
console.log("hey");
});
});
Seeing as you want to attach an event to the image, instead of iterating to each image, you could bind the event handler like this:
$("table").on("eventname", "td:first-child img", function(i){
//your code
});
Demo : http://jsfiddle.net/hungerpain/PYFhw/
I would like to use jQuery to select all rows in a table that don't have a td containing certain text.
I can select the rows with this line:
var x = $('td:contains("text"):parent'); //muliple td's in each tr
How would I use the :not selector to invert the selection?
edit: I don't think the line of code above is really accurate. This is how I originally had the line:
var x = $('td:contains("text")).parent(); //muliple td's in each tr
When I tried to invert the selection, I get all the rows as they all happen to contain a td not containing the text.
Try this:
var $x = $('td:not(:contains("text")):parent');
FIDDLE DEMO
Case 1: Select all TR that contains text 'my text' in all TD's
I wouldn't rely too much on the pseudo. Try something like below using filters, (internally pseudo are going to do the same anyway)
$('tr').filter(function () {
return $(this).find('td').filter(function () {
return $(this).text().indexOf('myText') == -1;
}).length;
}); //would return all tr without text 'myText'
DEMO: http://jsfiddle.net/dWuzA/
Case 2: Select all TR that contains text 'my text' in any TD's
#squint made an excellent point in comment
So incase if you want to select all TR that contains doesn't has a specific text in any of the TD's, then you can inverse the conditions.. See below,
DEMO: http://jsfiddle.net/dWuzA/1/
$(function () {
$('tr').filter(function () {
return !$(this).find('td').filter(function () {
return $(this).text().indexOf('22') != -1;
}).length;
}).addClass('highlight');
});
I have a scenario like
<table>
<thead>
<tr>
<th id ="myid1">header1</th>
<th id ="myid2">headre "2</th>
<th id ="myid3">header3</th>
</tr>
</thead>
<tr>
<td>v1</td>
<td>v2</td>
<td>v3</td>
</tr>
<tr>
<td>v10</td>
<td>v11</td>
<td>v12</td>
</tr>
<tr>
<td>v20</td>
<td>v21</td>
<td>v22</td>
</tr>
<tr>
<td>v30</td>
<td>v31</td>
<td>v32</td>
</tr>
</table>
there can be thousands of row .
i need to get the id of the td on which that perticulat td belongs to.
for example . if i click the third td of third row .. i should get the id of corresponding th , here it is myid3 (here its hard coded but it will set based on the value from server side)
$('tbody td').live('click', function() {
var idOfTh = ??
});
$(function(){
$('td').click(function() {
alert($('table th').eq($(this).index()).attr('id'));
});
});
Working JSfiddle: http://jsfiddle.net/6etRb/
You only need to use live delegation if the table rows are being added dynamically, and in that case you should use .on() as described by others.
You can use eq() method, try the following:
$('tbody td').live('click', function() {
var ind = $(this).index()
var idOfTh = $('thead th:eq('+ind+')').attr('id')
});
Please note that live() is deprecated you can use on() instead.
First of all, the .live() function has been deprecated. If you want to delegate events, use either .on() (jQuery 1.7+) or .delegate(). I'll assume you're using .on() for the rest of this, but there's only a minor syntax change (switch the first two arguments) if you have to use .delegate().
$(document).on('click', 'tbody td', function() {
var tdIndex = $(this).index();
// ^ gets the index of the clicked element relative to its siblings
var thId = $('thead th:eq(' + tdIndex + ')')[0].id;
// ^ selects the th element in the same position in its row, then gets its id
});
The following answer is wrong, but I'm keeping the edit as it may help someone
$('tbody td').live('click', function() {
var tdIndex = $(this).parent('tr').indexOf($(this));
var idOfTh = $(this).parent('table').find('tr').eq(tdIndex);
});
Untested, but theoretically should work.
CORRECTION
The above is incorrect, as pointed out by Felix Kling below. The correct way to get the index is simply by calling $(this).index(). I had presumed this would find the position of $(this) within the matched selector (in this case, every <td> in the <tbody>), but actually, if you pass the index() function no arguments, it finds the index relative to its siblings. Thanks to Felix for pointing out the relevant documentation.
Here's a way you could do it:
$('td').click(function() {
var colNum = $(this).parent().children().index($(this)) + 1;
alert($('#myid' + colNum).text());
});
jsfiddle: http://jsfiddle.net/p8SWW/4/
The handler can looks like:
function() {
var self = this
var th_num = 0;
$(this).parent().children().each(function(num){
if (this == self) {
th_num = num;
return false
}
});
var th_id = $('thead th').eq(th_num).attr('id');
}
Let's say I have a table column with 10 rows, each with <td id="num"> and a text value.
How can I use JQuery to loop through each row in the column and input the spins into a Javascript array?
I thought the following code would do it, but it is only getting the first element:
var numArray = [];
$("#num").each(function(n){
numArray[n] = $(this).text();
});
Any ideas?
Thanks!
You can't have multiple elements with the same id. This isn't allowed because the id is used to identify individual elements in the DOM. I'd suggest giving them all the same class, which is allowed.
<td class="num">
Then this should work:
var numArray = [];
$(".num").each(function(n){
numArray[n] = $(this).text();
});
Like mcos said, selecting by id for all the tables doesn't work. There can only be one item on a page with a given id.
You can either give your table an id and do the following:
var numArray = [];
// Assuming #my-table-id is your table and you want all the tds
$("#my-table-id td").each(function(n){
numArray[n] = $(this).text();
});
Or if you don't want all the tds, use a class to identify the ones you want
var numArray = [];
// Assuming #my-table-id is your table and you added class="collect"
// to the tds you want to collect
$("#my-table-id td.collect").each(function(n){
numArray[n] = $(this).text();
});
Also stealing from others answers, the map function can also help you make your code even smaller
var numArray = $.map( $("#my-table-id td.collect"), function (td){
return $(td).text();
})
You can achieve the this with using .text(function(i, text){})
var allText = [];
$("table td").text(function(i, t){
allText.push(t);
});
Code example on jsfiddle
If you need to target a particular cell(s) you can just modify the selector.
$("table td#num").text(function(i, text){
allText.push(text);
});
With that being said, an id should be unique per dom and if you can adjust the html using a class would be the right way.
<td class="num">
some text 1
</td>
$("table td.num").text(function(i, text){
allText.push(text);
});
Example
it's advised that use don't reuse the ID but since it'll html.. it'll still work..
the jQuery ID(#) selector will only select the first match...
you can use the td[id^='num'] or td[id*='num'] or td[id$='num'] instead
use the map ..
var numArray = $("td[id^='num']").map(function(){
return $(this).text();
}).get();
This will select all the td's with ID's starting as num
See it here
I know how to append a new row to a table using JQuery:
var newRow = $("<tr>..."</tr>");
$("#mytable tbody").append(newRow);
The question is how do I create a new row that precedes some existing row.
var newRow = $("<tr>...</tr>");
$("#idOfRowToInsertAfter").after(newRow);
The key is knowing the id of the row you want to insert the new row after, or at least coming up with some selector syntax that will get you that row.
jQuery docs on after()
where_you_want_it.before(newRow)
or
newRow.insertBefore(where_you_want_it)
-- MarkusQ
Rather than this:
$("#mytable tbody").append(newRow);
you are going to want to do something like this:
$("#id_of_existing_row").after(newRow);
With:
var newTr = $('<tr>[...]</tr>');
You can…
Insert it after (or before if you so choose) another row for which you know an ID (or whatever other property):
$('#<id of the tr you want to insert the new row after>').after(newTr)
Insert it after a particular row index (indices are 0-based, not 1-based):
$($('table#<id> tr')[<index>]).after(newTr)
…or as you mentioned, the absolute middle is possible:
var existingTrs = $('table#<id> tr')
$(existingTrs[parseInt(existingTrs.length / 2)]).after(newTr)
If for example u place an insert image into your table this will be something like this :
Your last cell in your table :
<td> <img class=\"insertRow\" src=\"/images/imgInsertRow.jpg\" /> </td>
Your jquery code :
$('table td img.insertRow').click(function(){
var newRow=$('<tr>........</tr>');
$(this).parent().parent().after(newRow);
});