how to get columns of selected rows using jquery - javascript

I tried with below code and getting alert of the column name but didn't get all columns of the multiple selected rows. Here is the sample code.
$('body').on('click', 'td', function() {
var selectedRows= $(this).toggleClass('selected');
var holdNames = $(this).closest("tr").find("td:eq(2)").text();
$("#holdNames").val(holdNames);
var holdsArr = [];
for ( var index=0; index<selectedRows.length;index++) {
holdsArr.push(holdNames[index]);
};
alert(holdsArr);
});

The below code will alert the 3rd <td> in each selected row
e.g. Text1,Text2,Text3
$('body').on('click', 'tr', function() {
$(this).toggleClass('selected');
var holdNames = $(this).children().eq(2).text();
$("#holdNames").val(holdNames);
var selectedRows= $('tr.selected');
var holdsArr = [];
for ( var index=0; index<selectedRows.length;index++) {
var name = selectedRows.eq(index).children().eq(2).text();
holdsArr.push(name);
};
alert(holdsArr);
});
A better approach would be
var holdsArr = [];
$(document).on('click','tr',function(){
var $tr = $(this);
$tr.toggleClass('selected');
updateHoldsArr();
alert(holdsArr);
});
function updateHoldsArr(){
var $trs = $('tr.selected'),
arr = [];
$trs.each(function(){
arr.push($(this).children().eq(2));
});
holdsArr = arr;
}

Related

Need to get the table row data for which cell is selected using jQuery

Have small requirement, I have to select multiple cells in a table. Once we click on submit button we have to show the respective row data of the each cell in alert message.
I tried with below code, im getting cell data, but getting trouble to fetch row data of respective cell. Can any one help me pls,
Here is the sample code.
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'td', function () {
$(this).toggleClass('selected');
// alert(table.cell( this ).data());
} );
$('#button').click(function() {
var rowdata = table.rows('.selected').data();
var cellData = table.cells('.selected').data();
//console.log(cellData);
var consoleMsg = '';
for (var i = 0; i < cellData.length; i++) {
consoleMsg += cellData[i]+'\n';
//consoleMsg += rowdata[i]+'\n';
}
alert(consoleMsg);
});
});
Fiddle
I found the solution you need. Try this:
$(function () {
var table = $('#example').DataTable();
var columnsNames = table.settings()[0].aoColumns.map(function (column) {
return column.sTitle;
});
$('#example tbody').on('click', 'td', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
var selectedCells = table.cells('.selected');
var selectedCellsAddresses = selectedCells[0];
var selectedCellsData = selectedCells.data();
var selected = [];
var columnName;
selectedCellsAddresses.forEach(function (cell, index) {
if (!selected[cell.row]) {
selected[cell.row] = {};
}
columnName = columnsNames[selectedCellsAddresses[index].column];
selected[cell.row][columnName] = selectedCellsData[index]
});
console.log(selected);
alert(JSON.stringify(selected));
});
});
Fiddle
you can do whatever you want with that selected variable. :)

Adding checkbox selected values in multi-dimensional array

I am working on this demo. How can I add each selected row as an array into the data [] so that it looks like this:
[{"Cell phone":"BlackBerry Bold 9650","Rating":"2/5","Location":"UK"},
{"Cell phone":" Samsung Galaxy","Rating":"3/5","Location":"US"}]
Here is the code I have:
var data = [];
function myfunc(ele) {
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
check if this works,
here is the fiddle demo
var data = [];
function myfunc(ele) {
var values = [];
var keys = [];
$.each($("input[name='case[]']:checked").closest("table").find('th'),
function () {
keys.push($(this).text());
});
keys.shift(); // to remove the first key
var len = keys.length, obj={}, ctr=0;
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
obj[keys[ctr]]=$(this).text();
ctr++;
if(ctr==len){
values.push(obj);
obj={};
ctr=0;
}
});
alert("val---" + JSON.stringify(values));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
http://jsfiddle.net/ugdas2em/
Try this:
var data = {};
function myfunc(ele) {
//var values = new Array();
var k = 0;
var j = 0;
data[k] = {};
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
if(j==3)
{
k = k+1;
data[k] = {};
j = 0;
}
//values.push($(this).text());
data[k][j] = $(this).text();
j=j+1;
});
console.debug(data);
//alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
Note: If you want then you can use [] with data variable in place of {} in my code. You need to replace at three place. Thanks.

Cannot search multiselect after modification

I have 2 multi selects in a page, and I need to transfer some of the option in first into second, while mantaining the search capabilities.
The problem is, that when I use the search input, it restores the selects to their original options...
Here is the jquery search function:
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
Here is the js fiddle : http://jsfiddle.net/C2XXR/ !
*I believe the problem lies in the options variable, but have no idea on how to solve it *
Thanks!
I have updated the fiddle. http://jsfiddle.net/C2XXR/2/
I have updated the code for right and left transfer. You have to change the option array itself got the filter, adding them in the dom will not work. In the changed code one issue is once we add from right to left or left to right it is getting added in the last position of the target select.
Please check and let me know if this is what you want.
Below is the main changed function. Later you can create a common function i suppose. Code can be optimized more.
$('[id^=\"btnRight\"]').click(function (e) {
var selected = $(this).parent().prev('select');
var target = $(this).parent().next('select');
target.find('option[value="999"]').remove()
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#isselect_code');
selected.data('options', tempOption);
});
$('[id^=\"btnLeft\"]').click(function (e) {
var selected = $(this).parent().next('select');
var target = $(this).parent().prev('select');
var options = selected.data('options');
var selectedVal = selected.find('option:selected').val()
var tempOption = [];
$.each(options, function(i) {
var option = options[i];
if(option.value != selectedVal) {
tempOption.push(option);
}
});
if( tempOption.length == 0 )
{
// add 999 here
}
var targetOptions = target.data('options');
targetOptions.push({value: selected.find('option:selected').val(), text: selected.find('option:selected').text()});
target.data('options', targetOptions);
selected.find('option:selected').remove().appendTo('#canselect_code');;
selected.data('options', tempOption);
});
the problem with your code is that after you click btnRight or btnLeft your collection of options for each select is not updated, so try after click on each button to call your filterByText as the following :
$('[id^=\"btnRight\"]').click(function (e) {
$(this).parent().next('select').find('option[value="999"]').remove()
$(this).parent().prev('select').find('option:selected').remove().appendTo('#isselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).parent().next('select').find('option:selected').remove().appendTo('#canselect_code');
$('#canselect_code').filterByText($('#textbox'), true);
$('#isselect_code').filterByText($('#textbox1'), true)
});

Get text from row column

I am only getting back the entire row as a object, what I am trying to get is the second column's row data.
$('#table_id tbody').on('click', 'tr', function (e) {
var nTr = this;
var i = $.inArray(nTr, anOpen);
var aPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(aPos[0]);
console.log(aData[0]);
if (i == -1) {
$(this).addClass('row_selected');
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr, 1), 'details');
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
}
else {
$(this).removeClass('row_selected');
$('div.innerDetails', $(nTr).next()[0]).slideUp(function () {
oTable.fnClose(nTr);
anOpen.splice(i, 1);
});
}
});
$('#table_id tbody').on('click', 'tr', function (e) {
var secondColumn = this.cells[1]; // returns HTMLTableCellElement
Now you can work with secondColumn to get all the data you need, such as secondColumn.innerHTML. If you need to work with the cell in jQuery, just use
var secondColumn = $(this.cells[1]);
instead.
var table = document.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++) {
var cell = rows[i].getElementsByTagName('td')[2];
var cellText = cell.childNodes[0];
if(cellText.data == '02/06/2010') {
// do something with cell
}
}
Try it here http://jsfiddle.net/ANsUq/

How to hide DIVs using a class name?

My code:
var array1 = document.getElementsByClassName("div");
var array2 = document.getElementsByClassName("button");
for(var i = 0; i < array1.length; i++)
{
$(array2[i]).show();
$(array1[i]).hide();
$(array2[i]).click(function(){
$(array1[i]).slideToggle();
});
}
Why I got error:
Could not convert JavaScript argument arg 0?
var $buttons = $(".button").hide();
$(".div").show().bind("click", function(event) {
var index = $divs.index(this);
$buttons.eq(index).slideToggle();
});
OR:
var $buttons = $(".button").hide(),
$divs = $(".div").show();
$.each($buttons, function(index) {
var $button = $(this);
$divs.eq(index).bind("click", function() {
$button.slideToggle();
});
});
OR
var $buttons = $(".button").hide(),
$divs = $(".div").show();
$buttons.each(function(index) {
var $button = $(this);
$divs.eq(index).bind("click", function() {
$button.slideToggle();
});
});

Categories