get html table column id with jquery - javascript

I have a html Table with 1 row and 1 column like this:
<table id="backlog">
<colgroup> <col width="200"></colgroup>
<tbody>
<tr><td id="91" tabindex="0" class="mark">BackLog</td></tr>
</tbody>
</table>
and I want to get the column id with jquery. How coul i do this?
I have tried this:
colId = $("#backlog td:first").attr('id');
but its not working.

If you're getting an undefined error with the posted code, it's likely that the DOM is not loaded by the time you're running the jQuery function. Make sure you wait for the DOM to load before you execute your jQuery:
$(document).ready() {
colId = $("#backlog td:first").attr('id');
}
Or, alternatively, the jQuery shortcut:
(function($){
colId = $("#backlog td:first").attr('id');
}(jQuery));

Assuming there will only ever be the one row/col
var colId = $("#backlog td").attr("id");

Try
$(function () {
colId = $("#backlog td:first").attr('id');
});

Related

Check if variable exists in a html table with javascript

I have two tables at the moment. What Im looking to achieve is to select a row in one table, obtain the "filename" field from that and then check if that filename exists in the other table. If the file exists in both tables I want to change the colour of my progress tracker. Right now I have the selecting of the row working, but I can't seem to check it against the other table. Any help would be greatly appreciated.
HTML:
<table id="table">
<tr>
<td>--</td>
<td>Filename</td>
</tr>
<tr>
<td>1</td>
<td>Example1</td>
</tr>
<tr>
<td>2</td>
<td>Example2</td>
</tr>
</table>
<table id="table2">
<tr>
<td>--</td>
<td>Filename</td>
</tr>
<tr>
<td>1</td>
<td>Example1</td>
</tr>
</table>
<div id="words">
</div>
JavaScript:
$("#table").find("tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:nth-child(2)').html();
//alert(value);
document.getElementById("words").innerHTML = value;
});
Thanks again for the help!
$("#table").on('click','tr',function(){ // <-- #1
var $this = $(this), // <-- #2
filename = $this.find('td:nth-child(2)').text(), // <-- #3
$words = $('#words');
$this.addClass('selected').siblings().removeClass('selected');
$words.html(filename).css('color','black');
if ( valueInTable('table2', 1, filename ) ){ // <-- #4
$words.css('color', 'blue');
}
});
function valueInTable(tableID, columnNum, searchString){
var found = false;
$( '#' + tableID + ' tr td:nth-child(' + columnNum + ')' ).each(function(){
if ($(this).text() == searchString ){
found = true;
return false;
}
});
return found;
}
This is important, this binds the event to the table. When a click occurs somewhere inside the table it checks the event registry, in this case, it checks to see if a TR was clicked. This is both a performance gain, since you're not creating an event for each row of the table, but also if you create new rows dynamically, you don't have to create a new event when you do. You create this event once and it's in place for all new/old rows of the table
Cache $(this) into a variable. You use it more than once and chances are you'll use it even more. You should not create a new jQuery object every time you want to refer to $(this), so stick it in a variable and reuse that
While .html() may work for you, if you have other embedded HTML, you might get values you were not intending (e.g., <span>filename</span>), for that reason, you only need .text(), which will just give you the text value and strip off all the nested HTML (leaving you with only filename)
Using a function comes with a penalty, but it's good to put long-logic elsewhere, in case you're doing anything more involved. For instance, your table could expand in width (number of columns) and you might also want to search them for a value, or you might have more tables you want to look in; this same function can be used for both of those cases.
as noted, the :contains() selector was built for what you're after However, there is one caveat. The problem with contains is that it lacks customization. If you want to modify your comparison to be a RegEx, or if you want to perform other manipulation using trim or truncate, you can't do that with contains. You could easily modify the code below to do: $.trim( $(this).text() ) == $.trim( searchString )
As #Pete commented, you can use if ($('#table2 td:contains(' + value + ')').length) as follows
$("#table").find("tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:nth-child(2)').html();
//alert(value);
if ($('#table2 td:contains(' + value + ')').length) {
document.getElementById("words").innerHTML = value;
} else {
document.getElementById("words").innerHTML = "false";
}
});
See the JSFiddle for working example: https://jsfiddle.net/v14L4bqr/

Getting the value of TD in a foreach loop

I have this code which show me the list of my item
<tbody class="table-color2">
<c:forEach var="defect" items="${defectList}">
<tr>
<td id="defectId"><a onclick="getDefectId()">${defect.id}</a></td>
<td>${defect.createdDate}</td>
<td>${defect.reportedBy.firstName}</td>
<td>${defect.title}</td>
<td>${defect.bugtype.description}</td>
<td>${defect.status.description}</td>
<td>${defect.priority.description}</td>
</tr>
</c:forEach>
</tbody>
what Im trying to do is to get the value of the td id="defectId" when it is clicked, my jquery script for the onclick is this :
function getDefectId(){
var defectId = $(' #defectId ').val();
alert("Defect ID " + defectId);
}
but currently, I'm getting a value of undefined, how do I get the value?
You have several issues. Firstly you're appending the same id in a loop, which will result in duplicates which is invalid. Also, a elements don't have a value to retrieve so you need to use text(). Finally note that using your current method would mean that you need to pass the this reference of the clicked element to the function.
However you can tidy all that up by using classes and hooking up the event in JS. Try this:
<tbody class="table-color2">
<c:forEach var="defect" items="${defectList}">
<tr>
<td class="defect">${defect.id}</td>
<td>${defect.createdDate}</td>
<td>${defect.reportedBy.firstName}</td>
<td>${defect.title}</td>
<td>${defect.bugtype.description}</td>
<td>${defect.status.description}</td>
<td>${defect.priority.description}</td>
</tr>
</c:forEach>
</tbody>
$(function() {
$('.defect a').click(function(e) {
e.preventDefault();
console.log($(this).text());
});
});
Working example
You can do the following(remember that id needs to be unique):
<td class="defectId"><a onclick="getDefectId(${defect.id})">${defect.id}</a></td>
And in you function:
function getDefectId(value){
alert("Defect ID " + value);
}
Try this : use text() instead of val() because you want to know the text inside td and not the value of input element.
EDIT: - Sorry, missed that there are multiple td's. In this case, you must not use same id for all tds. Just make it class and do following changes in function.
function getDefectId(){
var defectId = $('.defectId').text();
alert("Defect ID" + defectId);
}
I would suggest to use jQuery event handler instead of calling javascript function. See below code
HTML: remove onclick call
<td class="defectId">${defect.id}</td>
jQuery : register a click handler and read text
$(function(){
$('.defectId a').click(function(){
var defectId = $(this).text();
alert(defectId);
});
});

Getting the cell of a <tr> that has particular className

What i'm trying to do is to get the cell of this where the classname is "revision_id".
<tr>
<td class="supplierOrderId">10790</td>
<td class="revision_id">#7</td>
<td class="supplier">DGI Developpement </td>
<td class="quantity">80</td>
<td class="stock">0</td>
<td class="purchase_price">10.00</td>
<td class="comments"> </td>
</tr>
I managed to do it this way :
revision = this.parentNode.parentNode;
revisionId = revision.cells[1].innerHTML.replace( /[^\d.]/g, '' );
(cause I wanna get the int of the string)
iRevisionId = parseInt(revisionId);
Is there a more proper way to do it, with the given className ?
Because in the case where someone adds a cell before mine in the future, my code is going to be "deprecated".
Hope i've given all the details,
Thanks by advance.
// More Details //
The problem with most answers is that they work only if I have 1 <tr>. Once I get multiple, it gets every revisionID like this :
console.log(result) -> #1#2#3#4
(if I have 4 <tr> for exemple)
So this is why I am getting the GOOD one like this :
revision = this.parentNode.parentNode; // outputs the good <tr>
but after that, I can't get the with the given className.
if this is tr
var data = $(this).children(".revision_id").text()
Using the text() method, you can get the text inside your td element.
After that just parse it like you did with parseInt()
$(function() {
var quantity = $('tr td.quantity').text();
console.log(parseInt(quantity));
});
you can do via jquery like this:
var value= parseInt($(".vision_id").text().match(/[0-9]+/g)[0]);
FIDDLE EXAMPLE
Depends on whether you can use jQuery or not.
Pure JavaScript
With pure JS, provided you're using a modern browser, you can use the getElementsByClassName function. For the purpose of this demonstration, I've assumed you have an ID on your table you can use.
var myClassName = 'revision_id';
var table = document.getElementById('mytable');
// the desired TD
var td = table.getElementsByClassName( myClassName ) );
See Mozilla's docs on getElementsByClassName.
Also, this answer works with backwards compatibility.
jQuery
Of course, this becomes easier with jQuery:
var $td = $('#mytable td.revision_id');
Demo here: http://jsfiddle.net/uJB2y/1/
Well if you want it with jquery then you can use .filter() method:
var text = $('td').filter(function () {
return this.className === 'revision_id';
}).text().slice(1);
text = +text; // conversion for int
alert(text);
Demo

Select div text next to clicked button within table row

Here is a sample table.
<table class="table table-bordered">
<tbody>
<tr>
<tr>
<td>Stuff<div id="ParentID" style="display:none">145689</div></td>
<td><button class="btn btn-small">Send</button></td>
</tr>
</tbody>
</table>
I want to select the text within the div tag where id=ParentID that is closest to that button clicked. I will have multiple row in the future so it has to be unique to that row.
I have right now
var qry = $(this).closest('#ParentID').text();
Doesn't work obviously
This is how it can be done:
$(".btn").on("click", function() {
var text = $(this).closest("tr").find("div").text();
// ...
});
Note that elements should have unique IDs, so there can't be several <div> elements with ID "ParentID". I hope you use it as example only.
try this
$(".btn").on("click", function() {
$(this).parent('tr').find('div#ParentID').text();
});
$('button').click(function(){
var dataYouWant = $(this).parent().find('div').html();
});
You could do this, which gives the result:
$('.btn').click(function() {
alert($(this).parent().prev().children('div').text());
});
Try it out here: http://jsfiddle.net/YLcjf/2/
(I guess you should benchmark all these solutions. Not sure if 'find' has some greedy algortithm penalty associated with it)
$("button").click(function(){
alert($(this).parents("tr")
.find("div#ParentID").text());
});
JS Fiddle to test: http://jsfiddle.net/leniel/suRfG/

Open link when doubleclicking on table row with jQuery

I have a table that looks like this:
<table id="table">
<thead>
<tr class='tablehead'>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr class='tablecell'>
<td>
</td>
</tr>
</tbody>
</table>
I want to be able to double click on a row and then trigger a link.
An ID has to be transmitted somehow. Where should I define this? This allows me to edit the selected row afterwards.
Any idea how to do this?
Do you have any jQuery you've written yet? Here's a headstart...
Define your ID in the row:
<tr id="something">...</tr>
Then use something like this:
$('tr').dblclick(function(){
var id = $(this).attr('id');
//do something with id
})
This may help you:
jQuery(function($) {
$('#table tr').click(function() {
return false;
}).dblclick(function() {
window.location = url;
return false;
});
});
Do you mean something like this:
$(document).ready(function() {
$('.tablecell').click(function() {
return false;
}).dblclick(function() {
window.open("your_url");
return false;
});
});
and you could create a hidden field and populate that field with the id when double clicked.
Working demo: http://jsfiddle.net/Xr7LC/ (created from the sample code you provided)
Use dblclick api http://api.jquery.com/dblclick/
You can use $(this).attr('id') to get the id, and obviously you will define the id in a tag.
jQuery code for dblclick:
$(document).ready(function() {
$('#table >thead > tr').dblclick(function() {
alert('Row dblclicked');
alert($(this).attr('class'));
});
});​

Categories