I am trying to insert buttons into the JQuery DataTables but it seems that when the button is pressed, nothing happen.
The code as follows (for the JQuery Datatable):
var oTable = $('#example').dataTable( {
"aaData": movieclips,
"bProcessing": true,
"bAutoWidth": false,
"fnInitComplete": function() {
var oSettings = this.fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
$("tfoot input")[i].className = "";
}
}
},
"aoColumns": [
{
"sTitle": "Title",
"sClass": "center",
"sWidth": "80%"
},
{
"sTitle": "Video URL",
"sClass": "center",
"fnRender": function(obj) {
var sReturn = obj.aData[ obj.iDataColumn ];
var returnButton = "<input class='approveButton' type='button' name='" + sReturn + "' value='Play'></input>";
return returnButton;
},
"sWidth": "20%"
}
]
} );
The approveButton function as follows:
$(".approveButton").click(function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
Any Insight?
If you assign the handler with $(".approveButton").click(...) it will only apply to elements that already exist which match the ".approveButton" selector at that moment. That is, elements created later will not automatically get handlers of their own. I'm assuming that that is the problem - if not you can disregard the following...
Fortunately there is a mechanism for creating a handler that will automatically work on matching elements that are created in the future:
$(document).on("click", ".approveButton", function() {
// your function code here
});
Notice that the initial selector is document - this will work, but you should set it up on a parent element closer to your buttons if you can, so perhaps the following:
$("#example").on("click", ".approveButton", function() { /* your code */ });
(I'm not sure if "#example" is the most appropriate parent for this purpose, but you don't show any of your HTML, so...)
Have a look at the jQuery doco for .on() for more information.
Or, if you're using a version of jQuery older than 1.7 you can use `.delegate()'
If you use jquery < 1.7 you should use delegate() or live()
$(".approveButton").live('click', function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
$("body").delegate(".approveButton", "click", function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
otherwise use on() as suggested by nnnnnn
Related
Ok so I have this datatable with around 90 fields being populated from a dbContext (Visual Studio MVC4). I added the .makeEditable() to enjoy inline editing...
Most of my fields are of a type string (but a user CAN input a date if he opts to....even though its a text type field, the date will be input as simple text..)
The problem I have is that even though I'm successfully being able to get the class of the edit form to become "datepicker", the calender isn't popping up and on other simple non-datatable pages, it runs just fine.
I want to be able to set certain column cells to have inline datepicking ability..
I want my table to look like this thing http://jquery-datatables-editable.googlecode.com/svn/trunk/inline-edit-extra.html
I tried mimic-ing the code there but with no success....its always a textbox for editing instead of a calender view..
UPDATE: I noticed that if I change the "type:" field in
$.fn.editable.defaults = {
name: 'value',
id: 'id',
type: 'datepicker',
width: 'auto',
height: 'auto',
event: 'click.editable',
onblur: 'cancel',
loadtype: 'GET',
loadtext: 'Loading...',
placeholder: 'Double-Click to edit',
loaddata: {},
submitdata: {},
ajaxoptions: {}
};
My entire table gets a datepicker on editing mode...
Apparently the intializing code to give certain columns datepicker options doesn't work as it should ....or at least I guess so
**UPDATE END****
This is my datatable initialization code:
<script language="javascript" type="text/javascript">
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
});
$(document).ready(function ()
{
$('#myDataTable thead tr#filterrow th').each(function () {
var title = $('#myDataTable thead th').eq($(this).index()).text();
$(this).html('<input type="text" onclick="stopPropagation(event);" placeholder="Search ' + title + '""style="direction: ltr; text-align:left;" />');
});
$("#myDataTable thead input").on('keyup change', function () {
table
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
var table = $('#myDataTable').DataTable({
//"scrollY": "200",
"scroller": "true",
"deferRender": "true",
"orderCellsTop": "true",
"columnDefs": [
{ "visible": false, "targets": 1 },
{ "type": "datepicker", "aTargets": [6,7,8,9,10] },
{ 'sClass':"datepicker", "aTargets": [6, 7, 8, 9, 10] }
],
"order": [[1, 'asc']],
"displayLength": 25,
"drawCallback": function (settings)
{
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="88">' + group + '</td></tr>'
);
last = group;
}
});
},
"fndrawCallback": function (settings) {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
}
});
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.header()).on('keyup change', function () {
that
.search(this.value)
.draw();
});
});
// Order by the grouping
$('#myDataTable tbody').on('click', 'tr.group', function () {
var currentOrder = table.order()[0];
if (currentOrder[0] === 1 && currentOrder[1] === 'asc') {
table.order([1, 'desc']).draw();
}
else {
table.order([1, 'asc']).draw();
}
});
//$('#myDataTable thead').append($('#myDataTable thead tr:eq(0)')[0]);
$('#myDataTable').dataTable().makeEditable({
"aoColumnDefs": [
{ "type": "hasDatepicker", "aTargets": 4 },
{ "sClass": "hasDatepicker", "aTargets": 4 }
]
});
});
function stopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
} else {
evt.cancelBubble = true;
}
}
this is the datepicker.js
// add :focus selector
jQuery.expr[':'].focus = function (elem) {
return elem === document.activeElement && (elem.type || elem.href);
};
$.editable.addInputType(' datepicker', {
/* create input element */
element: function (settings, original) {
var form = $(this),
input = $('class ="datepicker" <input />');
// input.attr('class', 'datepicker');
input.attr('autocomplete', 'off');
form.append(input);
return input;
},
/* attach jquery.ui.datepicker to the input element */
plugin: function (settings, original) {
var form = this,
input = form.find("input");
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
onSelect: function () {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
onClose: function () {
setTimeout(function () {
if (!input.is(':focus')) {
// input has NO focus after 150ms which means
// calendar was closed due to click outside of it
// so let's close the input field without saving
original.reset(form);
} else {
// input still HAS focus after 150ms which means
// calendar was closed due to Enter in the input field
// so lets submit the form and close the input field
form.submit();
}
// the delay is necessary; calendar must be already
// closed for the above :focus checking to work properly;
// without a delay the form is submitted in all scenarios, which is wrong
}, 150);
}
};
if (settings.datepicker) {
jQuery.extend(datepicker, settings.datepicker);
}
input.datepicker(datepicker);
}
});
So after a lot of trial and error.....
I manually input the type of each of my 90 columns, and it manually worked....columnDefs with targeting a list of columns is probably bugged as in jeditable.datepicker it doesn't parse a list of columns passedin the settings....
Hope this helps a lost soul later on...
I give up as I have been messing around with this for the past 4 hours and I am just not getting anywhere. When using the jquery datatable found here. http://datatables.net/examples/api/editable.html (seems like a very popular plug in) I can get pretty much everything I want to work except the editable cell part. I have my file in this order
<script src="JS/jquery.js"></script>
<script src="JS/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="JS/jquery.jeditable.js"></script>
<script src="JS/jquery.validate.js"></script>
<script src="JS/ColReorder.min.js"></script>
<link href="JS/css/jquery.dataTables.css" rel="stylesheet" />
and then I have this script to get the table initialized.
function formattable(thistable) {
//alert(thistable + " from format table")
// $(document).ready(function () {
// ADPControlProcessor_Table1
//$("#ADPControlProcessor_GridView1").dataTable();
var oTable = $("#ADPControlProcessor_GridView1").dataTable({
//"bFilter": true,
"sScrollY": "200px",
"bPaginate": false,
"bAutoWidth": false,
"sDom": 'Rlfrtip'
//});
//alert("running");
});
//var oTable = $('#example').dataTable();
/* Apply the jEditable handlers to the table */
$('td', oTable.fnGetNodes()).editable('../examples_support/editable_ajax.php', {
"callback": function (sValue, y) {
var aPos = oTable.fnGetPosition(this);
oTable.fnUpdate(sValue, aPos[0], aPos[1]);
},
"submitdata": function (value, settings) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition(this)[2]
};
},
"height": "14px"
});
I dont know what elese to try. can anyone point me in the right direction.
Instead of paying for the editable plugin I built my own which you're free to use. The repo is here: DataTables CellEdit Plugin
The basic initialization is quick and easy:
oTable.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
myCallbackFunction = function (updatedCell, updatedRow) {
console.log("The new value for the cell is: " + updatedCell.data());
}
you are not initialize correct Try this one
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#example').dataTable();
/* Apply the jEditable handlers to the table */
$('td', oTable.fnGetNodes()).editable( '../examples_support/editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
} );
here is live example click here
The problem i am having with me JQuery function is that it only works when i refresh the webpage, it is working this way on every browser. What i am trying to do is once all of the textfields in enclosed in a specific div container all have data inside them, i want the the container to insert the checkmark image. but currently this image only becomes visible after i have entered all of the data in the textfields AND refreshed the brower.
.rightbilling is the class of the div container whose textfields im trying to evalute and '#step1' is the fieldset that contains .rightbilling.
I have been trying to solve this for hours..help is greatly appreciated. if you need more info, let me know.
$(document.body).ready(function() {
var all_complete = true;
$(".rightbilling").find("input:text").each(function(){
if ($(this).val() == '' ) {
all_complete = false;
return true;
};
if (all_complete) {
$("#step_1")
.animate({
paddingBottom: "120px"
})
.css({
"background-image": "url(images/check.png)",
"background-position": "bottom center",
"background-repeat": "no-repeat"
});
$("#step_2").css({
opacity: 1.0
});
$("#step_2 legend").css({
opacity: 1.0 // For dumb Internet Explorer
});
};
});
Because you're using the document.ready function, your function is only being called when the page loads. You'll want to look into attaching an onChange listener to call your function when the input fields have been changed.
$(document.body).ready(
function () {
var validation = function () {
var all_complete = true;
$(".rightbilling").find("input:text").each(
function () {
if ($(this).val() == '') {
all_complete = false;
return true;
}
if (all_complete) {
$("#step_1").animate({
paddingBottom: "120px"
}).css({
"background-image": "url(images/check.png)",
"background-position": "bottom center",
"background-repeat": "no-repeat"
});
$("#step_2").css({
opacity: 1.0
});
$("#step_2 legend").css({
opacity: 1.0 // For dumb Internet Explorer
});
}
});
}
validation(); //call it when the page is loaded
$(".rightbilling").find("input:text").on("change",validation); //call it when input changes
}
);
Using datatables. The problem is $('.checkbox') click function only works on first page of datatables, nowhere else. Note that, $('#check_all') works on every page.
JS looks like that:
function changeQt(){
if($('#quantity').is(':hidden'))
$('#quantity').fadeIn("slow");
$('#quantity').animate({
borderColor: "#00a9e0"
}, 'fast').text(totalqt).delay(400).animate({
borderColor: "#fff"
}, 'fast');
}
function doIt(obj) {
if ($(obj).is(":checked")) {
$(obj).closest("tr").not('#hdr').addClass("row_selected");
totalqt=totalqt + parseInt($(obj).closest("tr").find("#qt").text(), 10);
}
else {
$(obj).closest("tr").not('#hdr').removeClass("row_selected");
totalqt=totalqt - parseInt($(obj).closest("tr").find("#qt").text(), 10);
if(totalqt<0) totalqt=0;
}
}
function checkAllCheckboxes(isChecked) {
if(isChecked ){
totalqt=0;
}
$('.checkbox').each(function(){
$(this).prop('checked', isChecked);
doIt(this);
});
changeQt();
}
$(document).delegate('td.item_id', 'click', function(e){
e.stopPropagation();
});
$(document).delegate('#list > tbody > tr', 'click', function(){
window.open($(this).attr("url"));
});
$(document).ready(function() {
$("input:submit, input:reset").button();
$.datepicker.regional[""].dateFormat = 'dd.mm.yy';
$.datepicker.setDefaults($.datepicker.regional['']);
$('select[name=list_length]').change(function(){
if ($('#check_all').is(':checked'))
$('#check_all').click();
});
var oTable= $('#list').dataTable( {
"bJQueryUI": true,
"iDisplayLength": 25,
"aaSorting": [],
"aoColumns": [
{
"bSortable": false
},
null, null, null,null,null, null, null
]
} ).columnFilter({
sPlaceHolder: "head:before",
aoColumns: [ null, null, null,null,null, null, null,
{
type: "date-range"
}
]
});
$('.checkbox').click(function(e) {
e.stopPropagation();
doIt(this);
changeQt()
});
$('select[name=list_length]').change(function(){
if($('#check_all').is(':checked')){
$('#check_all').prop('checked', false);
checkAllCheckboxes(false);
}
});
$('#check_all').click(function(){
checkAllCheckboxes(this.checked);
});
});
Here is 1 row from this table:
<tr url="?page=item&id=1411">
<td class="item_id"><input type="checkbox" name="checkbox[]" method="post" value="1411" class="checkbox"/> 1411</td>
<td> 9814</td>
<td style="text-align:center">BK</td>
<td style="text-align:center">36</td>
<td style="text-align:center" id="qt">1</td>
<td style="text-align:center">15</td>
<td style="text-align:center">12</td>
<td>15.02.2012</td>
</tr>
If someone want to see page in action, please join discussion: Here.
I assume dataTables is adding/removing elements from the DOM, and with them will go the event handlers attached to them.
Instead of attaching events by the shortcuts (eg click(), or blur()) which will only work when the element in question is available on page load, use delegate() (or on() in jQuery 1.7+)
$("#list").delegate('.checkbox', 'click', function(e) {
e.stopPropagation();
doIt(this);
changeQt()
});
jQ 1.7+
$("#list").on('click', '.checkbox', function(e) {
e.stopPropagation();
doIt(this);
changeQt()
});
The FAQ about events will be of some use to you here: http://datatables.net/faqs#events . It also includes examples of how to apply the solution. In this case I would suggest using:
table.$('.checkbox').click(function(e) {
where table is the DataTables instance. The $ API method will give you a jQuery object that will operate on all rows in the table, regardless of current paging.
I have a page that call from ajax a form with a specific target. this form has a delete entry and for that a warning with a jQuery dialog is used. everything works great.
BUT :
After doing the change or even not doing it, when I open another form (different form by ajax call) and I call the same code below described. When It is submit the dialog the #var_blabla as a value of 1 (the value of the first dialog opened/loaded) and for that moment should be '2'.
I try to figure it out.. So my problem I guess is not for the dialog it self, since I try to load a second page without the constructor and the dialog didn't open (what should be expected).
The problem is on the button 'Submit Delete' that has an event function and it stays active over another that is created.
The site have a lot of forms and many dialogs for each form, is there a wait to unbind, or destroy completely the dialog and the buttons? Ideas please?
Thanks
simplified 1st dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('1');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
simplified 2nd dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('2');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
UPDATE:
<script type="text/javascript">
submited=false;
var toggleOpened = true;
$("#admin_retractil_1").click(function () {
if(!toggleOpened){
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=true;
}
else{
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
var toggleOpened2 = false;
$("#admin_retractil_2").click(function () {
if(!toggleOpened2){
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=true;
}
else{
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
$(document).ready(function() {
//$( "button").button();
var locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$( "#EditDataForm" ).click(function() {
if(locked){
locked = false;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-unlocked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}else{
locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}
return false; });
$( "#DelDataForm").button({ icons: { primary: "ui-icon-scissors" }});
$( "#DelDataForm" ).click(function() {
$('#dialog-confirm-del').dialog('open');
return false; });
/*abre popup de alerta de eliminar */
arrayRemove.push("dialog-confirm-del");
$("#dialog-confirm-del").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Remove Stuff': function() {
$('#sel_action_form').val('TypoDesClients_DelDef');
$('#name').val('_____');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancelar: function() {
$(this).dialog('close');
}
}
});
$( "#AcceptChanges").button({ icons: { primary: "ui-icon-check" }});
$("#form_submeter").validator({
position: 'center right',
offset: [0, 0],
message: '<div><em /></div>'
}).bind("onSuccess", function(e, els) {
var numSucceeded = els.length,
numExpected = $(this).data('validator').getInputs().length;
if (numSucceeded === numExpected) {
if(!submited){submited=true;
SubmitFormSV('form_submit', 'action/action_a.php');
return false;
}else return false;
}
});
$( "#radio" ).buttonset();
$("#1_radio").click(function () {
$("#tr_1").show();
});
$("#2_radio").click(function () {
$("#tr_1").hide();
});
});
local lib:
function SubmitFormSV(formul, address)
{
DoChecks();
$("#loading").show("slow");
$.post(baseURL + address, $('#' + formul).serialize(), function(html){
$('#content').slideUp("slow", function () {
AjaxChargePage(html, true);
});
});
$("#loading").hide("slow");
return false;
}
next the next chuck of javascript is similar to this one.
and with this work because destroy didn't:
DoChecks() As:
$.each(arrayRemove, function() {
var element = arrayRemove.pop();
$('#'+element).remove();
});
When you're done with dialog 1 try...
$("#dialog-confirm-elimina").dialog("destroy");
or in your Cancel function...
$(this).dialog("destroy");
The .dialog command creates a new dialog on the element selected. You're doing this twice, and thus having problems. Once the dialog is created it can be reused using open and close methods or destroyed as I've shown above and then recreated.
Ok, then finally I got a solution that make everything works. Instead of using the
$("#dialog-confirm-elimina").dialog("destroy");
I use:
$("#dialog-confirm-elimina").remove();
I still don't know the reason but clearly don't have the problem anymore.
Thanks for the answer though.
PS: If anyone know how could this append I appreciate to illuminate me about it.Thanks