table row click event not working - datatables

Hello I'm new to the JavaScript world. i am pulling data from a database using coldfusion into a dataTable and i would like that when i click on a row in the datatable and event is fired which so that the details of that row can be displayed in divs on the same page.
Below is the code i am using but it is not working, i would appreciate it if someone could give me an example that works
<script type="text/javascript" class="init">
$(document).ready( function () {
var table = $('#expenseList').DataTable();
$('#expenseList tbody').on('click', 'tr', function () {
//var name = $('td', this).eq(0).text();
var name = table.row( this ).data();
alert( 'You clicked on '+name+'\'s row' );
} );
} );
</script>

Related

Data table on click on dynamic controls

I have a jquery data table that I am populating from a drop down on change event. I have two check boxes in the data table and I am running an onclick on the check boxes. But on the first click the jquery does not fire only when I click it a second time does the jquery fire, also happens on switching pages.I added the .on() for the click, because I researched and saw that dynamic controls would work that way. Is there something I'm missing also to get this click function to work on first click? Below is some of my code.
data table click on check box control no jquery click event on first click
data table click on check box control on second click
$('#my-table').on('click', function () {
var i = -1;
$("input[id*='secondary']:checkbox").on("click", function () {
if ($(this).is(':checked')) {
i = selectedIds.indexOf($(this).val());
if (i === -1) {
selectedIds.push($(this).val());
}
CheckedSecondary(this);
}
else {
jQuery(this).closest("tr").css("background-color", "");
if (selectedIds.length > 0) {
i = selectedIds.indexOf($(this).val());
if (i != -1) {
selectedIds.splice(i, 1);
}
}
if (!primaryChecked)
$(this).closest('tr').find('input[type="checkbox"]').not(this).attr('disabled', false);
}
});
$("#my-table").find("input[id*='primary']:checkbox").on("click", function () {
if ($(this).is(':checked')) {
primaryChecked = true;
primaryID = this.value;
CheckedPrimary(this);
}
else {
primaryID = "";
primaryChecked = false;
$(this).closest('tr').find('input[type="checkbox"]').not(this).attr('disabled', false);
$('input:checkbox[id^="primary"]').each(function () {
if (!$(this).closest('tr').find('input[type="checkbox"]').is(':checked'))
$(this).attr('disabled', false);
});
jQuery(this).closest("tr").css("background-color", "");
}
});
});
You're attaching click handler inside another click handler which doesn't make sense.
Remove first click handler:
$('#my-table').on('click', function () {
});
Attach the click handler to the checkboxes as follows:
$('#my-table').on('click', "input[id*='secondary']:checkbox", function () {
});
and
$('#my-table').on('click', "input[id*='primary']:checkbox", function () {
});

How to set cell value in DataTable on button click

I'm trying to modify a cell value using DataTable (the new version) when an outside button is clicked.
I have the following for now:
$(document).on('click', '.dropdown-menu li a', function () {
if ($(this).text() == "development") {
var cell = table.row( 6 ).data()[4]
cell.data( "development" ).draw();
}
});
This doesn't work since I think the table row and data retrieval method doesn't return an object with .data() attribute that allows me to set data cell value. I'm getting the following error: cell.data is not a function. (In 'cell.data( "development" )', 'cell.data' is undefined)However, I'm not sure how to access a table cell value the .data() way without having a click even in the table. My button is placed outside the table somewhere else.
Any idea how to make this work?
Since DataTables 1.10+ might not support fnGetNodes() as mentioned on the API landing page itself, instead now you can use rows().nodes().
Example: http://jsfiddle.net/cmedina/7kfmyw6x/28/
var table = $('#example').DataTable({sorting : false});
var row = table.row(0).node();
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
table.cell(row, 0).data('Development').draw();
}
});
If you work with DataTables < 1.10 then you can use fnUpdate
Example: http://jsfiddle.net/cmedina/7kfmyw6x/29/
var oTable = $('#example').dataTable({sorting:false});
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
oTable.fnUpdate('Development', 0, 0 ); // Single cell
}
})
you can use fnUpdate Datatables Function to update any specific cells just by row and col indexes.
something like this :
var oTable = $('#example').dataTable();
$('#button').click(function() {
var row = document.getElementById("indexDepRow").value;
var col = document.getElementById("indexDepCol").value;
oTable.fnUpdate('development', parseInt(row), parseInt(col));
});
See JsFiddle EXAMPLE

Get data object on row click

I am using jquery datatables and I am having trouble grabbing the row data on click event. How can I get my data object from my datatable on row click event?
What I do:
jquery post to get a json response load json response as data into datatable (array of objects)
jquery, register click event on
datatable rows when user clicks on row, need to get data object for
row clicked on
My current code:
function contactSearchListTable(data) {
// data is array of javascript object
console.log('contactSearchListTable()');
$(contactSearchResultsTableElement + ' tbody').off();
if ( $.fn.dataTable.isDataTable(contactSearchResultsTableElement) ) {
$(contactSearchResultsTableElement).DataTable().destroy();
}
if (data.length == 0) {
$(contactSearchResultsTableElement).html('');
}
var table = $(contactSearchResultsTableElement);
var params = {"data":data
,"info": false
,"searching": false
,"ordering": false
,"lengthChange": false
,"columns":[
{"data":"id","visible":false}
,{"data":"name","title":"Name","class":"clickable"}
,{"data":"phoneHome","title":"Home","class":"clickable"}
,{"data":"phoneWork","title":"Work","class":"clickable"}
]
};
var dt = table.dataTable(params);
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function () {
console.log(this); // <tr> html from datatable
// **** need to get hidden ID value here, HOW?
} );
}
You can access the data using row().data() function, change you click handler to:
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function (){
var data = dt.api().row(this).data();
});

TableView 'click' listener being ignored

I am dynamically building a TableView in my controller, which works fine: The initial table displays the initial collections data as expected.
The problem is that the TableView's 'click' event listener is ignored when I click on the table rows. I am testing in the browser, and I never even see the console event file (see comments in controller file). All relevant code snippets below:
In my alloy.js I setup a backbone collection:
function defaultTodo(name) { return {name: name, done: false}; }
function doneTodo(name) { return {name: name, done: true}; }
Alloy.Collections.todos = new Backbone.Collection();
Alloy.Collections.todos.reset([
defaultTodo('Apples'), // create not yet done todo
defaultTodo('Banana'),
defaultTodo('Paper Towels'),
defaultTodo('Broccoli'),
doneTodo('Beans'), // create already done todo
doneTodo('Water'),
doneTodo('Blueberries'),
doneTodo('Stir Fry')
])
Here is my index.js controller:
var todos = Alloy.Collections.todos;
function redrawTable() {
// clear all the old data
// See http://developer.appcelerator.com/question/49241/delete-all-rows-in-a-tableview-with-a-single-click
$.table.setData([]);
// Create and add the TableViewSections
var alreadyDone = Ti.UI.createTableViewSection({ headerTitle: "Already Done" });
var needsDoing = Ti.UI.createTableViewSection({ headerTitle: "Needs Doing" });
$.table.appendSection(needsDoing);
$.table.appendSection(alreadyDone);
// Add the todo to the appropriate sections
todos.forEach(function(todo) {
var section = todo.get('done') ? alreadyDone : needsDoing;
addEntry(todo, section);
});
// Add the click listener
// THIS LISTENER IS IGNORED ********************************
$.table.addEventListener('click', function(e) {
console.log(e);
todos.at(e.index).set('done', true);
todos.trigger('change');
});
// Helper function to add a row to a section
function addEntry(todo, section) {
var row = Ti.UI.createTableViewRow({
title: todo.get('name'),
className: "row"
});
section.add(row);
}
}
// Redraw our table each time our todos collection changes
todos.on('change', redrawTable);
// Trigger a change event to draw the initial table
todos.trigger('change');
$.index.open();
And here is index.xml view file:
<Alloy>
<Window class="container">
<Label id="test" class="header">My Grocery List</Label>
<TextField id="newItem"/>
<TableView id="table">
</TableView>
</Window>
</Alloy>
UPDATE: Working Code
In addition to the changes below, I also added onClick="markDone" to the xml.
function markDone(e) {
console.log(e.row.todo);
e.row.todo.set('done', true);
todos.trigger('change');
}
function redrawTable() {
// clear all the old data
// See http://developer.appcelerator.com/question/49241/delete-all-rows-in-a-tableview-with-a-single-click
$.table.setData([]);
var rows = [];
var done = [];
var doing = [];
// Add the todo to the appropriate sections
todos.forEach(function(todo) {
var row = Ti.UI.createTableViewRow({
title: todo.get('name'),
className: "row"
});
row.todo = todo;
todo.get('done') ? done.push(row) : doing.push(row);
});
// Create and add the TableViewSections
rows.push(Ti.UI.createTableViewSection({ headerTitle: "Needs Doing" }));
rows = rows.concat(doing);
rows.push(Ti.UI.createTableViewSection({ headerTitle: "Already Done" }));
rows = rows.concat(done);
$.table.setData(rows);
};
I created brand new project using files which you provided and eventListener is working perfectly fine. However there are couple other bugs:
Creating listener inside redrawTable() function, which is executed every time you click on something in TableView. As a result at the beginning you have one eventListener but after every click all listeners are duplicated.
Using index property in event handler to find index of Backbone model object to update. index property is indicating at which place given row was displayed in your TableView. When you are moving rows between sections their index are changing. In your case it's better to check e.row.name property and use Backbone.Collection.findWhere() method. If user can have two items with the same name on the list, then you have to create additional property to determine which object in model should be changed.
You should add rows to section before section are added to table. In your case table is very simple so instead of doing loops you can just create one simple array of objects (with title and optional header properties) and pass it to $.table.setData().
It's good to wait for postlayout event triggered on main view before triggering any custom events to make sure that the whole view was created and all objects are initiated.
Check rewrote index.js code below to see how it could be done.
var todos = Alloy.Collections.todos;
function redrawTable() {
var done = todos.where({done: true}).map(function(elem) {
return { title: elem.get('name') };
});
if (done.length > 0) {
done[0].header = 'Already Done';
}
var notdone = todos.where({done: false}).map(function(elem) {
return { title: elem.get('name') };
});
if (notdone.length > 0) {
notdone[0].header = 'Needs Doing';
}
$.table.setData( done.concat(notdone) );
}
$.table.addEventListener('click', function(e) {
todos.where({ name: e.row.title }).forEach(function(elem){
elem.set('done', !elem.get('done'));
});
todos.trigger('change'); // Redraw table
});
// Redraw our table each time our todos collection changes
todos.on('change', redrawTable);
// Trigger a change event to draw the initial table
$.index.addEventListener('postlayout', function init(){
todos.trigger('change');
// Remove eventListener, we don't need it any more.
$.index.removeEventListener('postlayout', init);
})
$.index.open();
redrawTable() could have a little more refactor but I left it so it's easier to read.
To read more about manipulating TableView check this Appcelerator documentation page.

Add row to gridview on client side

I have asp.net's .aspx page.
that have GridView let say GridViewParent and Each row have the another GridView as GridViewChild. Now GridViewChild have button AddRow and another controls like DropDownControl,RadioButtons..etc... I want after click the button AddRow there must add row on client side. How can i do same. Please guide me .... Send me code
<script type="text/javascript" src="../../js/jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#<%=cmdAdd.ClientID %>').bind('click', function(event) {
//debugger;
event.preventDefault();
var $grid = $('#<%=ctlGrid.ClientID %> ');
var $row = $grid.find('tr:last').clone().appendTo($grid);
$row.find('select')[0].selectedIndex = 0;
$row.find('input').each(function() {
$(this).val("");
});
return true;
});
});