Open link when doubleclicking on table row with jQuery - javascript

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

Related

Remove all <tr> If does not contain "test" in text

I am making a chrome extension for the first time and need a little help with my Javascript.
In my popup menu I want a few buttons. Once someone presses this button lets say button "test". I want it to remove every single <tr> whom does not contain the word "test".
I am making this because the filter functionality on this website I use a lot is very slow. This way I can filter faster myself by removing the rows instead of the program searching through all of them.
This is what I have so far:
var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
if ($(this).text() != searchString) {
$(this).parent().remove();
}
});
<p>Remove all rows which don't contain:</p>
<button onclick="Tester()">TEST</button>
Firstly don't use inline JS. It's bad practice. Attach event handlers using unobtrusive JS instead.
To fix your actual issue, use the :contains selector along remove(), something like this:
$('button').click(function() {
var searchString = $(this).text();
$("#tbody tr td:contains('" + searchString + "')").closest('tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Remove all rows which don't contain:</p>
<button>TEST</button>
<table>
<tbody id="tbody">
<tr>
<td>TEST</td>
</tr>
<tr>
<td>Foo</td>
</tr>
<tr>
<td>TEST</td>
</tr>
<tr>
<td>Bar</td>
</tr>
</tbody>
</table>
Try this
$("#tbody tr td").each( function () {
if ( $(this).text().indexOf( searchString ) == -1 ) { //notice the use of indexOf
$(this).parent().remove();//
}
});
Or you can check the row's text itself
$("#tbody tr").each( function () {
if ( $(this).text().indexOf( searchString ) == -1 ) {
$(this).remove();//
}
});

Get element attribute with .each loop

I have a simple example table that has data attributes for every table row.
<table id="example">
<tr data-sample="1">
<th>Fox</th>
<th>Sam</th>
<th>Ted</th>
</tr>
<tr data-sample="2">
<td>Bill</td>
<td>Nick</td>
<td>Pal</td>
</tr>
<tr data-sample="3">
<td>El</td>
<td>Pal</td>
<td>Tea</td>
</tr>
</table>
I'm trying to get all data-sample attributes with the following code:
('#example tr').each(function () {
console.log(this.data('sample'));
});
JSfiddle
And I'm getting a "this.data is not a function" error. This gets me to the point that in .each jquery loop this returns a DOM element, not a function or whatever I can use a a selector (if I just print out this, I get a list of table rows and their children). Is there any way to get this as a selector? ('#example').children('tr') and ('#example').find('tr') give the same result.
Jquery syntax error
this not jquery object .Do with $(this).data('sample')
$('#example tr').each(function () {
console.log($(this).data('sample'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a simple example table that has data-attributes for every table row.
<table id="example">
<tr data-sample="1">
<th>Fox</th>
<th>Sam</th>
<th>Ted</th>
</tr>
<tr data-sample="2">
<td>Bill</td>
<td>Nick</td>
<td>Pal</td>
</tr>
<tr data-sample="3">
<td>El</td>
<td>Pal</td>
<td>Tea</td>
</tr>
</table>
Or do with attr()
$('#example tr').each(function () {
console.log($(this).attr('data-sample'));
});
There are two issue in you code:
1) you need to convert DOM object to jquery object for using with .data()
2) you are passing wrong property argument in .data(). it should be sample:
$('#example tr').each(function () {
console.log($(this).data('sample'));
});
There are 2 way to do this -
#1
$('#example tr').each(function () {
console.log($(this).data('sample'));
});
#2
$('#example tr').each(function () {
console.log($(this).attr('data-sample'));
});
Check this
$(document).ready(function(){
$('#example tr').each(function () {
console.log($(this).attr("data-sample"));
});
});
If you want to get row content use this
$('#example tr').each(function (i) {
alert($('#example tr[data-sample]')[i].innerText.split("\t"));
});

Building an anchor menu automatically with jQuery

I need some help for doing a menu built automatically with jQuery.
I have the following HTML structure
<table width="99%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td height="20">Descripción</td>
</tr>
<tr>
<td height="20">Preguntas Frecuentes</td>
</tr>
<tr>
<td height="20">Incompatibilidades</td>
</tr>
</tbody>
</table>
...
<a name="descripcion"></a>
<h1>Descripcion</h1>
...
<a name="preguntas"></a>
<h1>Preguntas</h1>
In this case the anchor "incompatibilidades" doesn't exist, so what I need is to create a jQuery script which look for any "a" tag which has its corresponding link.
The result I expect is the following:
<table width="99%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td height="20">Descripción</td>
</tr>
<tr>
<td height="20">Preguntas Frecuentes</td>
</tr>
</tbody>
</table>
I'll appreciate your help!
If I understood correctly, you could do something like this:
var menu = $("#menu");
$("a").each(function() {
var $this = $(this);
var name = $this.attr("name");
if (typeof(name) !== 'undefined') {
var links = $("a[href='#"+name+"']");
var link;
if (links) {
link = links.eq(0);
}
if (link && typeof(link) !== 'undefined') {
menu.append("<tr><td><a href='#"+name+"'>"+link.text()+"</a></td></tr>");
}
}
});
You have to add "menu" id in a new table to create what you expect.
If you would like to remove the the table row which contains the mentioned anchor tag which does not exist, you could use:
$(document).ready(function() {
$('a[href="#incompatibilidades"]').closest('tr').remove(); // Or detach, possibly
});
If you would like to add in an h1 + a and append it to your DOM, you could use:
$(document).ready(function() {
var anchor = $('<a></a>', { 'name' : 'incompatibilidades' });
var h1 = $('<h1></h1>', { text: 'incompatibilidades' });
// Append these to the DOM here.
});
First, you shouldn't be using named anchors, but ids instead (the "name attribute on the a element is obsolete1"), to give:
<h1 id="descripcion">Descripcion</h1>
...
<h1 id="preguntas">Preguntas</h1>
Also, using a <table> element to present a list is a little non-semantic, since it's non-tabular information; instead use an ordered list, <ol>. So, with that in mind, I'd suggest the following jQuery:
$('h1[id]').each(function() {
var target = this.id;
$('#toc').append(function() {
return '<li>' + target + '</li>';
});
});
#toc {
text-transform: capitalize;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="toc"></ol>
<h1 id="descripcion">Descripcion</h1>
...
<h1 id="preguntas">Preguntas</h1>
This approach is based on an assumption that you want to build a table of contents to link to those elements that are on the page.
Notes:
http://www.w3.org/TR/html-markup/a.html#a-constraints.
Without testing, and if I get your question correct - you are looking for something like this:
$().ready(function() {
// scan all links in your menu
$('table').find('a').each(function() {
// grep href attribute
var target = $(this).attr('href');
// element does not exist?
if(! $(target).length) {
// remove parent row
$(this).closest('tr').remove();
}
});
});
And - as #David Thomas mentioned correctly, you shouldn't be using named anchors, but ids instead - if you do so, you can use the anchor ('#xyz') directly as id selector as I did in the function above.

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/

Jquery Datatables - Make whole row a link

This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
$('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
You can also use the DataTables plugins api which allows you to create custom renderers.
Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
**I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );

Categories