How the select the multiple Table data as per selected checkbox? - javascript

There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit

Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit

Related

jQuery TableSorter - textExtraction based on external variable

I have a TableSorted table, and in each TD element are five SPAN elements. Four are always hidden, but upon clicking a div outside the table, certain spans are hidden dependent on which div is clicked.
I have the table sorting fine, but what I need is for the textExtraction to grab a different SPAN, depending on the value of the div which has been selected.
I've tried the following to no avail:
textExtraction:function(node){
var filter=$("div.career a.sel").text();
if(filter=="a"){var theindex=0;}
if(filter=="b"){var theindex=1;}
if(filter=="c"){var theindex=2;}
if(filter=="d"){var theindex=3;}
if(filter=="e"){var theindex=4;}
return $(node).find("span").eq(theindex).text();
}
What is the best way to achieve this?
The textExtraction function is only called when tablesorter is initialized or updated. Try triggering an update after the selection has changed.
var indexes = 'abcde'.split(''),
// Is this a select box?
$sel = $("div.career a.sel").on('change', function(){
$('table').trigger('update');
});
$('table').tablesorter({
textExtraction: function(node){
// if this is a select, get val(), not text()
var filter = $sel.val(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Update: for a link, try this:
var indexes = 'abcde'.split(''),
$careers = $("div.career a").on('click',function(){
var searcher = $(this).attr("rel");
$("div.career a").removeClass("sel");
$(this).addClass("sel");
$("td.stat span").hide();
$("td.stat span.career_" + searcher).show();
});
$('table').tablesorter({
textExtraction: function(node){
// find selected
var filter = $careers.filter('.sel').text(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Note: Don't use live() in jQuery version 1.9+, it was removed.

Styling table according to its contents

I have the following table: http://jsfiddle.net/UfhVc/1/
I am trying to:
Get the same style on all rows who have the same ID
Highlight the differences in each on the rows with the same ID.
But right now I can't seem to figure out the logic needed for step 1). It's ok to use jQuery, I just found it easier to use plain js.
Also, I get a warning in this part of the code:
table.rows[i+1].cells[0].innerHTML
Like this?
var newColor = "#F1D0F2";
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () { //Loop through the trs leaving out the header
var txt = $(this).find('td:eq(0)').text(); //get the text of the id column
var $this = $(this);
var matchingRows = $('#tbl tr').not(this).filter(function () { //get the matching rows whose id colum value is same
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', newColor); //apply css for match
matchingRows.find('td').css('background-color', function (i) { //apply background color
if ($this.find('td:eq(' + i + ')').text() != this.innerHTML) return diffColor; // to the tds of matching rows but column valud differ.
});
});
Fiddle
References:
:gt()
filter()
css()
:eq()
Edit
Based on your comment here is the update:
var allColors = ["#333333","#990099", "#1295A6", "#FFFF99"]; //Set up the colors in to an array
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () {
var txt = $(this).find('td:eq(0)').text();
var $this = $(this);
if($this.is('.transformed')) //check for class transformed is present if so this has already been processed skip it.
return;
//Get the matching rows whose id column value is same
var matchingRows = $('#tbl tr').filter(function () {
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', allColors.shift()).addClass('transformed'); //Set the color and add a class to avoid latter processing
matchingRows.find('td').css('background-color', function (i) { //apply background color
var $parTd = $this.find('td:eq(' + $(this).index() + ')');
if ($.trim($parTd.text()) != $.trim(this.innerHTML)) // to the tds of matching rows but column value differ.
{
$parTd.css('background-color', diffColor);
return diffColor;
}
});
});
Fiddle
For step one:
There are a few ways you can do it, I would probably attach a class to all table cells which are of a certain type, so you can easily select them all at once for editing.
<table>
<tr>
<td class="id-cell"></td>
</tr>
</table>
Then you could simply query it with CSS like:
.id-cell {
background-color:red;
}
But you can also just use more jQuery / JavaScript to find those table cells you're looking for anyways. This fiddle uses jQuery to find all the cells which are in the "id" column, and paint the background red.
http://jsfiddle.net/8QL22/
Another way of doing it:
$("table tr:not(:first-child) td:first-child").each(function(index) {
var thisId = $(this);
$("table tr:not(:first-child) td:first-child").each(function(_index) {
if (index != _index && thisId.text() == $(this).text())
{
thisId.parent("tr").css("backgroundColor", "red");
$(this).css("backgroundColor", "red");
$(this).siblings("td").each(function(sindex) {
var other = $(thisId.siblings()[sindex]);
if (other.text() != $(this).text())
other.css("backgroundColor", "yellow");
});
}
});
});
http://jsfiddle.net/w4mvp/

Get An Element Within a Table Row

Firstly,
If possible, I would like to do this without JQuery, and purely Javascript.
Ok so I have an html table with rows getting added dynamically to it.
In each row is a:
Select Element (id = "ddFields")
Text Input Element (id = "tfValue")
Button Element (no id)
The Button Element removes the row for which it is situated
The Select Element has a default option of "" and then other 'valid' options
The Text Input is added to the row but it is hidden.
All elements are in the same
Basically I would like for the Select Element to show the hidden text input element if the selected index is != 0
so far I have this for my onchange function:
function itemChanged(dropdown) //called from itemChanged(this)
{
var cell = dropdown.parentNode;
var row = cell.parentNode;
var rowIndex = dropdown.parentNode.parentNode.rowIndex;
var index = dropdown.selectedIndex;
var option = dropdown.options[dropdown.selectedIndex].text;
if(index >0)
{
alert(row);
var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
alert(obj);
//row.getElementById("tfValue").hidden = "false"; //doesn't work
//row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
}
else
{
alert('none selected');
}
}
Finally figured it out. So here it is:
SCENARIO:
A table that has rows added to it dynamically.
In each row there is a select element and an input text element.
The select element changes text-value of the input text element based on the index of the select element.
in your select element set the onchange function to this:
onchange="selectionChanged(this)"
then create a javascript function shown below:
function selectionChanged(dropdown)
{
//get the currently selected index of the dropdown
var index = dropdown.selectedIndex;
//get the cell in which your dropdown is
var cell = dropdown.parentNode;located
//get the row of that cell
var row = cell.parentNode;
//get the array of all cells in that row
var cells = row.getElementsByTagName("td");
//my text-field is in the second cell
//get the first input element in the second cell
var textfield = cells[1].getElementsByTagName("input")[0];
//i use the first option of the dropdown as a default option with no value
if(index > 0)
{
textfield.value = "anything-you-want";
}
else
{
textfield.value = null;
}
}
Hope this helps whoever. It bugged me for a very long time. Thanks shub for the help! :)
first, I hope you are not repeating your ids. No two items should have the same id.
If you're iterating, create id1, id2, id3.
Also, this is not necessary but I suggest introducing your vars like this:
var a = x,
b = y,
c = z;
If you decide to use jQuery you could just do this:
$('#tableid').on('click','button',function(){
$(this).parent().parent().remove();
});
$('#tableid').on('change', 'select',function(){
if($(this).val()){ $(this).next().show(); }
});
Be sure to change #tableid to match your table's id.
This assumes the text input is the very next element after the select box. If not so, adjust as necessary or ask and I'll edit.

jQuery: Get next table cell vertically

How can I use jQuery to access the cell (td) immediately below a given cell in a traditional grid-layout html table (i.e., one in which all cells span exactly one row and column)?
I know that the following will set nextCell to the cell to the immediate right of the clicked cell because they are immediate siblings, but I am trying to retrieve the cell immediately below the clicked cell:
$('td').click(function () {
var nextCell = $(this).next('td');
});
Preferably I would like to do it without any use of classes or ids.
Try this:
$("td").click(function(){
// cache $(this);
var $this = $(this);
// First, get the index of the td.
var cellIndex = $this.index();
// next, get the cell in the next row that has
// the same index.
$this.closest('tr').next().children().eq(cellIndex).doSomething();
});
$('td').click(function () {
var index = $(this).prevAll().length
var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});
index is the 0-based index of the cell in the current row (prevAll finds all the cells before this one).
Then in the next row, we find the nth-child td at index + 1 (nth-child starts at 1, hence the + 1).
How about:
$('td').click(function () {
var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
If you want to do it without using selectors, you can do:
function getNextCellVertically(htmlCell){
//find position of this cell..
var $row = $(htmlCell).parent();
var cellIndex = $.inArray(htmlCell, $row[0].cells);
var table = $row.parent()[0];
var rowIndex = $.inArray($row[0], table.rows);
//get the next cell vertically..
return (rowIndex < table.rows.length-1) ?
table.rows[rowIndex+1].cells[cellIndex] : undefined;
}
$('td').click(function () {
var nextCell = getNextCellVertically(htmlCell);
//...
});
Not that efficiency is important here but it works out much faster to do it like this - in tests over 100,000 iterations it was 2-5 times faster than the selector based approaches.
Are there an equal number of cells in each table row? If so, you could get the "count" of the cell in question, then select the corresponding cell in the next('tr').

Customizing JQuery Cloned row attributes

I have been researching the JQuery way to add table rows dynamically. One excellent thread is: How to Copy Table Row with clone in jquery and create new Unique Ids for the controls, with the last example being the one I am targeting in this post.
I have a fiddle giving an example of what I am trying to do. This fiddle does not work exactly yet, but I am working on it,
The main issue I am having is getting the table row copy to set different types of column elements id and default values, and even row attributes. In essence, how do I extend this to be more robust.
Thanks to Nick Craver, I am trying to use this:
// do Add row options
$("#Add").click(function() {
var rowCount = $('#secondaryEmails >tbody >tr').length;
var i = rowCount + 1;
alert('rowCount: ' + rowCount + ', new row: ' + i);
$("#secondaryEmails >tbody tr:first").clone().find("input").each(function() {
$(this).attr({
'id': function(_, id) {
return id + i
},
'name': function(_, name) {
return name + i
},
'value': ''
});
}).end().appendTo("#secondaryEmails >tbody");
});
which will copy and insert a row nicely, but if I have a row with a radio button, input box, and select list, I cannot figure out how to tell it to set the default value of each element depending on the type of element. I am trying to use a template row, but that means I need to set the style:display attribute on the row from none to table-cell. Again, how?
Please see the fiddle mentioned previously for a working example.
This is now showing the row: http://jsfiddle.net/EwQUW/5/
You would want to use .show() on the element to show it, which effectively sets the style to display:block instead of display:none;
Try this http://jsfiddle.net/EwQUW/3/
// do Add button options
$("#Add").click(function() {
var i = ($('#secondaryEmails >tbody >tr').length)+1;
$("#secondaryEmails >tbody tr:first").clone().find("input,select").each(function() {
//if(this).(':radio').
$(this).attr({
'id': function(_, id) {
return id + i;
},
'name': function(_, name) {
if($(this).attr("type") == "radio")
return name;
return name + i;
},
'value': ''
});
}).end().appendTo("#secondaryEmails >tbody").show();
});
// do update button options
$("#update").click(function() {
// find and display selected row data
alert('in Update');
var rowCount = $('#secondaryEmails >tbody >tr').length;
});
// do row double click options
// do row selected by either focusing on email or ship type elements

Categories

Resources