jQuery get each <img> element within specific column of the table - javascript

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/

Related

Dynamically adding event handler to select box

I'm trying to dynamically add an event listener to a select box.
With this code I just don't get any response, so no alert box:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
$("sel1").on('change', function() {
alert(this.val());
});
table.append(row);
$('#mydiv').append(table);
Also, how can I add the select box between the td?
Currently, it's added between the tr, td simply isn't there.
Here is a fiddle
Updated Fiddle
You should use event delegation on() when you deal with fresh DOM added dynamically :
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
NOTES :
You should add id selector before sel1 it should be #sel1.
.val() is a jquery method you can't call it on javascript object like this.val() it should be $(this).val().
The current code will not add select inside td it will add it directely inside tr tag so you could replace :
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option>
<option>test2</option></select>');
By :
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>
test2</option></select></td>');
Hope this helps.
Working Snippet
var table = $('<table></table>');
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
table.append(row);
$('#mydiv').append(table);
td{
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
Couple of points to note in your code
1) Wrong Selector $("sel1")
The problem in your code is $("sel1") you need to select by id using # so it should be $("#sel1"). So your code would be like
$("#sel1").on('change', function() {
alert(this.val());
});
2) Bind event after appending the HTML to DOM or Use Event Delegation
Your code should be places in this order Working Fiddle
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);// now the element is added to DOM so bind event
$("#sel1").on('change', function() {
alert($(this).val()); // note here I changes this.val() to $(this).val()
});
Or another option is using event delegation Working Fiddle
To add event's to dynamic elements use the event delegation
$('body').on('change',"#sel1", function() {
alert($(this).val());
});
3) To place the select tag inside td use the below syntax
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
Wrap the td along with the select tag and not inside the tr Working Fiddle
You need to bind the change event after appending to the page:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);
$("#sel1").on('change', function() {
alert(this.val());
});
And also you have forgotten the # id selector for "sel1"
There are three major issues in your code
1.The id selector must start with #
$("#sel1").on('change', function() {
2.You should bind the change listener only after you appended the element, because it just doesn't exist in the DOM before
3.With
$('<tr><td></td></tr>')
you'll get a jquery reference to the row (the <tr> element). Then with .html() you are replacing the content of the row (including the <td> of course)

Why is this returning no elements?

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

jQuery parent() in table

I want to access the div tag in the following HTML code:
<table>
<div class="rowBound">
<tr onclick="expandLastResultDetails(this);">
<td class="c1">56835-14513</td>
...
</tr>
<tr class="rowDetails">
<td colspan="0">
<div style="background-color: #0F9;"> expandable
</div></td>
</tr>
</div>
</table>
But jQuery commands just give me a TBODY instead of my DIV ..
This is what I was doing in another case:
function expandNavContent(navEntryTitle) {
var content = $(navEntryTitle).parent().children('.navContent');
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
What I want:
rowDetails should be animated with slideToggle if someone clicks on the tr
If I use this code:
function expandLastResultDetails(tableEntry) {
var content =$(tableEntry).parent().children('.rowDetails');
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
It toggles ALL rows but it should just toggle ONE row so I nested them into a division, maybe that was wrong
Try this:
$('tr.rowDetails').find('div');
But, your Markup is not valid. tr is element of table, not for div.
To get the outer parent div:
$('tr.rowDetails').closest('div');
After edit
function expandLastResultDetails(tableEntry) {
var content =$(tableEntry).next('.rowDetails'); // will point to next tr
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
Try $('.rowDetails').closest('div.rowBound');
It will bubble from the current element (outwards) until it find a div element.
Hope it helps
What command did you try? You could have used this:
$(".rowDetails tr td div");
And moreover, there cannot be a <tr> inside a <div>!
Since your markup is invalid the browser will propably insert the tbody and table for you (look at the markup in FireBug/Dev tools). Something like $(".rowDetails").parent().parent().parent() could work (in some browsers) but I'd recommend fixing the markup instead

How to get the Id of corresponding th of td in a table

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

Display jQuery-ui dialog box if <div> is not empty

I have a div block like this:
<div id="myDiv">
<table>
<tbody>
<tr>Some data</tr>
</tbody>
</table>
</div>
All I want to do is check if the <tr></tr> has some text in it and display this div block in a dialog box, otherwise don't do anything.
What would be the best way to do this? I don't know how to check if the <tr></tr> is empty or not.
First of all you have invalid html. The tr tag can contains one or more th or td elements (W3C). So fix your html.
As for validation using jQuery:
if ($('#myDiv table tr td').is(':empty')) {
}
else {
}
http://jsfiddle.net/JnyJs/1/
DEMO
var text = $.trim($('#myDiv').text());
if (text) {
alert(text);
}
You can check the "emptiness" usng jQuery's .text() function:
var $tr = $('#myDiv > table > tbody > tr');
if ($tr.text())
{
// div is not empty
}
else
{
// div is empty
}
You may want to $.trim() the whitespace from the returned string.

Categories