Deactivate click-Event for last column - javascript

On my js I set a click-Event for each table-row.
This works fine atm.
I try to remove the click-Event just for the last column of this table, but it doesn't work.
Do you have an idea why? Is the selector right or do I have to select more than just the last-child of td?
function addRowHandlers() {
var table = document.getElementById("klauselliste");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function (row) {
return function () {
var cell = row.getElementsByTagName("td")[0];
var name = cell.innerHTML;
window.location.href = '/Klausel/Detail?Name=' + name.trim();
};
};
currentRow.onclick = createClickHandler(currentRow);
}
// Code Snippet
addRowHandlers();
$("td:last-child").unbind("click");
// Code Snippet

I recreated your code as "pure jQuery". Less code, same effort. Note the :not(:last-child), it will select all td of a row, execpt the last.
function addRowHandlers() {
$("table#klauselliste tr td:not(:last-child)").click(function() {
var name = $("td:eq(0)", $(this).parent()).html();
window.location.href = '/Klausel/Detail?Name=' + name.trim();
});
}
See here for an working example: https://jsfiddle.net/wuhtt7sc/1/

Try using .find() to locate the last element on your table.
$('#klauselliste tr').find('td:last').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
});

Related

`search` text only considered the last column in the table

I am trying to implement a search functionality in to an table. some thing went wrong here, put the search(filter) only considers the last column of the table.
any one help me to find out the issue please?
here is the live :
jsFiddle
my js:
var table = $('table');
$('#search').keyup(function () {
var tdText = table.find('tbody tr').find('td');
var text = $.trim($(this).val());
if(!text){
table.find('tbody tr').show();
};
tdText.filter(function() {
var reText = $(this).text();
if (reText.indexOf(text) >= 0) {
$(this).parent('tr').show();
}
else if (reText.indexOf(text) < 0) {
$(this).parent('tr').hide();
}
});
});
because when you iterating through each td, you are hiding the tr if the text is not matching so when you are iterating the last td you are hiding the row if the text is not matched
var table = $('table');
$('#search').keyup(function () {
var tdText = table.find('tbody tr').find('td');
var text = $.trim($(this).val());
if(!text){
table.find('tbody tr').show();
}else{
table.find('tbody tr').hide();
tdText.filter(function() {
var reText = $(this).text();
return reText.indexOf(text) >= 0;
}).parent().show();
}
});
Demo: Fiddle
I think you can simplify it to
var table = $('table'), $trs = table.find('tbody tr');
$('#search').keyup(function () {
var tdText = table.find('tbody tr').find('td');
var text = $.trim($(this).val());
if(!text){
$trs.show();
}else{
$trs.hide().has('td:contains('+text+')').show();
}
});
Demo: Fiddle
var tdText = table.find('tbody tr').find('td');
Will find multiple td's. This line loops through the elements and replaces tdText with the next column till last is reached.
Solution is to loop yourself
var tablecells = $('table tbody tr').find('td');
var rowText = "";
$(tablecells).each(function() {
rowText = rowText + trim($(this).val());
});
You are going through all td of all tr, but for each td you show or hide the parent row based on the search result for that td – so naturally only the result for the last td checked is what “survives” in the end for each row.
First of all, you need to split your loop, that goes over all td of all tr in one go, into two nested loops – one over the tr, and inside that one over all td of that row.
And then you should set a flag to determine whether something was found in any of the td in the row – and then at the end, you show or hide the row based on that flag.
var table = $('table');
$('#search').keyup(function () {
var text = $.trim($(this).val());
if(!text){
table.find('tbody tr').show();
}
else {
var rows = table.find('tbody tr');
rows.each(function() {
var cells = $(this).find('td'),
found = false;
cells.each(function(j, cell) {
if($(this).text().indexOf(text) >= 0) {
found = true;
}
});
if(found) {
$(this).show(); // this is here the row again
}
else {
$(this).hide();
}
});
}
});
Untested – but something along these lines should work.
Notice that I replaced .filter by .each here – your use of the former made little sense, since you where not actually doing any filtering here (that would have required that your callback function returned true or false for each element).

How to get th when child td is clicked?

I trying to get the <th> content of the clicked <td> item.
here is the fiddle: http://jsfiddle.net/zrccq447/
the thing is, the <th> can have colspan 2 or 3, this is the point where I am stuck. this is my code
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + (clicked_pos) + ')').text();
var xy = td.text();
alert(x);
});
i want x to be the <th> of clicked td. the problem is now that if you click on some td that shares the th with other tds, i am getting the wrong th.
appreciate any help
I've updated your JsFiddle with the answer found here: Finding a colSpan Header for one of the cells or td's is Spans
JsFiddle: http://jsfiddle.net/zrccq447/4/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + thLocator[clicked_pos] + ')').text();
var xy = td.text();
alert(x);
});
var thLocator = [], colCount = 1;
$('#table9').find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
Following on from my comment you need to sum up the colspans (or default 1) for each TH until you get enough to match the column you desire:
http://jsfiddle.net/TrueBlueAussie/zrccq447/5/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var cols = 0;
var $table = td.closest('table');
var $ths = $table.find('tr th');
for (var i = 1; i < $ths.length; i++) {
var $th = $ths.eq(i);
cols += ~~$th.attr('colspan') || 1;
if (cols >= clicked_pos) {
var x = $th.text();
alert(x);
break;
}
}
});
I tried to keep it generic, so it finds the appropriate table and headers on the fly.
One approach is to get store a reference to each TH, in order, in an array and call the text from the array based on the location of the td.
var thholder = $('table th'),
th = [];
for(var i = 0; i < thholder.length; i++) {
var thi = $(thholder[i]);
for(var j = 0; j < (thi.attr('colspan') || 1); j++) {
th.push(thi);
}
}
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
alert(th[clicked_pos].text());
});
http://jsfiddle.net/zrccq447/3/
This code is not optimised, but shows the approach:
Loop through all the TH in the table.
If the TH does not have the attribute 'colspan', then set the attribute to a value of 1.
Create a loop for each value of colspan and save a reference to the current TH in the array.
When you click on a TD, get it's clicked position and retrieve the text of the TH at that position in the array and alert it :)

Could you please help me to highlight the selected HTML table row created dynamically through java script

Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!

Javascript table row <tr> onclick function not executing

I'm trying to have each table row clicked to be highlighted in a color and I'm handling this with a class name but the onclick function is not executing, I tried print statement inside the onclick function to check if it is entering but it's just not.
Here is the JS code related to that part:
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
Anyone know why this function isn't getting entered?
EDIT: I realized the mistake in the rows variable and I corrected it but the function is still not getting entered and I have no errors on my JS console
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
row.className = "highlighted";
};
};
currentRow.onclick = createClickHandler(currentRow);
}
Use this it will works....
Use this code. Your table rows must have an attribute name with the value "tr" to make this work :
var rows = document.getElementsByName("tr");
for (var i = 0; i < rows.length; i++)
{
rows[i].onclick = function() {
this.className = "highlighted";
}
}
use getElementsByTagName instead of getElementsById.
Try this
var rows = document.getElementsByTagName("tr");
Add semicolon
rows[i].onclick = function() {
this.className = "highlighted";
}; // here
It works for me .. Check here : JS Fiddle

Arrange the numbers in input name element array from zero up after remove a input

I want after remove one of the rows (Ex: Row 2) in html code changed to in name element by jQuery.
For example we first have in html as:
Row 1: name="check[0][]"
Row 2(removed): name="check[1][]"
Row 3: name="check[2][]"
Row 4: name="check[3][]"
Now if we remove the second row, In fact, after removed the row 2, we have rows like this:
Row 1: name="check[0][]"
Row 3: name="check[2][]"
Row 4: name="check[3][]"
But i want it in result (after remove one of rows ex: row 2) as:
Row 1: name="check[0][]"
Row 3: name="check[1][]"
Row 4: name="check[2][]"
I tried as (see my full code) but Don't work: http://jsfiddle.net/k3wne/
Js:
$('.remove_input').live('click', function (e) {
e.preventDefault();
var remove = $(this).closest($class);
remove.fadeOut('slow', function () {
$('.add_units').each(function (idx, val) {
var num = $('.add_units').length;
NumIdx = (num - (num - idx));
//for(var i = 0; i < num-1; i++){
$(this).closest($class_guide).next($class_guide).each(function (idx, val) {
$('.add_units input[type="checkbox"]').attr('name', function (idx, str) {
var int = parseInt(str.match(/\d+/)[0], 10);
return str.replace(int, NumIdx);
})
});
//}
})
});)
}​
Here
DEMO
$('.remove_input').live('click', function (e) {
e.preventDefault();
var remove = $(this).closest('.RowCheck');
remove.fadeOut('slow', function () {
$(this).remove(); // or change next line to $('.RowCheck:visible')
$('.RowCheck').each(function (idx) {
var checkBoxes = $('input[type="checkbox"]',this);
checkBoxes.each(function(i) {
var str = $(this).attr('name');
var currentIdx = parseInt(str.match(/\d+/)[0], 10);
$(this).attr('name', str.replace(currentIdx,idx));
})
});
});
});​
This code will work if you either
remove the row for real - also suggested by Explosion Pills or
test for visible like Simon did
http://jsfiddle.net/k3wne/1/
A couple of things: You never actually remove the element once it's faded out which screws up your counts, and the last selector (.RowCheck input[type="checkbox"]) affects all checkboxes so they will all have the highest number.
In my changes, only the current row in the iteration is affected.
Most of you code is correct, however the some changes needed:
change to use $('.RowCheck:visible').each()
as fadeOut is just hide that row but not really delete, and the inner loop should use $('input[type="checkbox"]', this)
Code looks something like following:
$('.remove_input').live('click', function (e) {
e.preventDefault();
var remove = $(this).closest('.RowCheck');
remove.fadeOut('slow', function () {
debugger;
$('.RowCheck:visible').each(function (idx, val) {
var num = $('.RowCheck:visible').length;
NumIdx = (num - (num - idx));
//for(var i = 0; i < num-1; i++){
//$(this).closest('.RowCheck').next().each(function (idx, val) {
$('input[type="checkbox"]', this).attr('name', function (idx, str) {
var int = parseInt(str.match(/\d+/)[0], 10);
return str.replace(int, NumIdx);
})
//});
//}
});
});
});​
DEMO

Categories