I just implemented a DataTable in my app, but it seems like javascript doesn't work within the DataTable.
I've attached all code below for better readability.
As you can see, the ccbtn_action="delete" bit is present, but Chrome/IE/FF doesn't seem to want to do anything when the glyphicon is clicked.
This code works perfectly when called from outside the DataTable.
What gives? Is it something to do about JavaScript not being applied to dynamically generated elements?
Thank you!
Here is the Javascript code that doesn't work:
$(document).ready(function(){
// Delete Records
$('[ccbtn_action="delete"]').on('click', function() {
var type = $(this).attr('ccbtn_value_type');
var value = $(this).attr('ccbtn_value_id');
console.log('type=' + type + '&id=' + value);
if (confirm('Are you sure you want to PERMANENTLY delete this record? There is NO TURNING BACK!')) {
$.ajax({
type: 'POST',
url: 'includes/crmcore_action.php?action=cc_delete',
data: 'type=' + type + '&id=' + value,
success:
function() {
$('#cc_pagetop_status').html("<div class='alert alert-success'><strong>Success!</strong> The record was successfully deleted.</div>");
if (type == "company")
{
window.location = "companies_list.php";
}
else
{
location.reload();
}
}
});
} else {
// Do nothing!
}
});
});
Here is the code for the DataTable:
$(document).ready(function() {
var t = $('#DataTable').DataTable({
"order": [[ 1, 'asc' ]],
ajax: {
url: 'includes/dt_ss.php?getwhat=company',
dataSrc: ''
},
columns: [
{data: null},
{"data": null,
"render": function (data, type, row)
{
return ''+data.name+'';
}
},
//{data: 'name'},
{data: 'tel'},
{
"data": "id",
"render": function ( data, type, full, meta )
{
return '<span class="glyphicon glyphicon-remove" ccbtn_action="delete" ccbtn_value_type="company" ccbtn_value_id="'+data+'" data-toggle="tooltip" data-placement="bottom" title="Click me to delete"></span>';
}
}
],
});
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
Since the js looks ok, this is most probably a timing issue. You part of script that binds the events is executed before the actual elements are created.
To fix that, you can:
Make sure the script runs binding after elements creation
Use dynamic binding (like .delegate() http://api.jquery.com/delegate/)
Try delegating your event like this:
$('#DataTable').on('click', '[ccbtn_action="delete"]', function() { ...
My guess is the click event is attached before your ajax request loads the DataTable rows. You can read more here about jQuery event delegation with on(). Specifically:
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
Try like this, but jquery version must be 1.9+
$(document).on('click', '[ccbtn_action="delete"]', function() { // your remaining code
Related
So I'm getting data from a back-end through an AJAX GET method, and presenting it in a list(below) in html. I tried to put the button tag in there and I get the buttons on the list but I'm not sure how to use the delegate and others to make it work.
So how can I put independent buttons that send the users to a details page about the cafeteria in that list? (This is just a personal project)
$(function(){
var $cafeterias = $('#cafeterias');
var $Name = $('#CName');
var $Location = $('#CLocation');
function DispCafeteria(cafeteria) {
$cafeterias.append('<li> Name: '+cafeteria.Name+'Location: '+cafeteria.Location+'<button id="Details">Details</button>'+'</li>');
}
$.ajax({
type: 'GET',
url: 'some url',
success: function (cafeterias) {
$.each (cafeterias, function (i, cafeteria){
DispCafeteria(cafeteria);
});
},
error: function() {
alert('Error while loading cafeterias');
}
});
});
A few nit pick:
Don't name functions with a leading capital letter unless your planning to instantiate it (constructor function). It confuses people since this is the common de facto standard.
Avoid nested callback logic. Use a promise interface instead. (jQuery has one).
Don't construct interactive DOM elements with HTML strings. It makes it difficult to attach events to it. An exception is using event delegation which in your example is a better more performant way to do that.
You should break your problem space down. Separate concerns into smaller chunks.
Fetch AJAX Data:
function fetchData() {
return $.ajax({
type: 'GET',
url: 'some url'
});
}
Handle errors:
function handleErrors(err) {
alert('Error while loading cafeterias');
}
Construct the DOM:
function cafeteriaToString(cafeteria) {
return 'Name: ' + cafeteria.name +
' Location: ' + cafeteria.location;
}
function constructDataTable(cafeterias) {
$.each(cafeterias, function (i, cafeteria) {
var $button = $('<button/>')
.text('Details')
.data('details-id', i);
$('<li/>')
.text(cafeteriaToString(cafeteria))
.append($button);
});
}
Attach a delegated event:
function handleButtonClicks(e) {
var detailsId = $(this).data('details-id');
// Do something with detailsId
}
Putting it all together:
function init() {
fetchData()
.then(constructDataTable)
.fail(handleErrors);
$('ul').on('click', 'li>button', handleButtonClicks);
}
I generate a dropdownList dynamicly with jquery Ajax , generated dropdown's id
is specificationAttribute . I want create add event for new tag was generated (specificationAttribute) , to do this I created Belowe script in window.load:
$(document).on('change', '#specificationattribute', function () {
alert("Clicked Me !");
});
but it does not work .
I try any way more like click , live but I cant any result.
jsfiddle
Code from fiddle:
$(window).load(function () {
$("#specificationCategory").change(function () {
var selected = $(this).find(":selected");
if (selected.val().trim().length == 0) {
ShowMessage('please selecet ...', 'information');
}
else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: { categoryId: categoryId, controlId: 'specificationattribute' },
type: 'POST',
success: function (data) {
$('#specificationattributes').html(data);
},
error: function (response) {
alert(response.error);
}
});
}
});
$(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});
}
Your fiddle has syntax errors. Since a dropdownlist generates a select, let's use one.
For my answer I used THIS HTML, more on this later: things did not match in your code
<select id="specificationAttribute" name="specificationAttribute">
</select>
Code updated: (see inline comments, some are suggestions, some errors)
$(window).on('load', function() {
$("#specificationCategory").on('change',function() {
var selected = $(this).find(":selected");
// if there is a selection, this should have a length so use that
// old: if (selected.val().trim().length == 0) {
if (!selected.length) { // new
// NO clue what this is and not on the fiddle so commented it out
// ShowMessage('please selecet ...', 'information');
alert("select something a category");// lots of ways to do this
} else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: {
categoryId: categoryId,
controlId: 'specificationattribute'
},
type: 'POST',
success: function(data) {
// THIS line id does not match my choice of specificationAttribute so I changed it
$('#specificationAttribute').html(data);
},
error: function(response) {
alert(response.error);
}
});
}
});
// THIS should work with the markup I put as an example
$(document).on('change', '#specificationAttribute', function() {
alert("changed ");
});
});// THIS line was missing parts
#Uthman, it might be the case that you have given different id to select and using wrong id in onchange event as i observed in the jsfiddle link https://jsfiddle.net/a65m11b3/4/`
success: function (data) {
$('#specificationattributes').html(data);
},and $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
}); $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});.
It doesnt work because at the moment of attaching event your html element doesnt existi yet.
What you need are delegated events. Basically, you attach event to parent element + you have selector for child (usually by classname or tagname). That way event fires for existing but also for elements that meet selector added in future.
Check documentation here:
https://api.jquery.com/on/#on-events-selector-data-handler
Especially part with this example:
$( "#dataTable tbody" ).on( "click", "tr",
function() {
console.log( $( this ).text() );
});
i got an asp.net mvc project, but actually most of functions i achieved via javascript, below screenshot is the part which makes me frustrating, here you can see i use a date picker to define time slot then filter content for next dropdown button with related contents.
$('.input-daterange').datepicker({
format: "yyyymm",
minViewMode: 1,
language: "zh-CN",
beforeShowMonth: function (date) {
switch (date.getMonth()) {
case 0:
return false;
case 1:
return false;
case 2:
return false;
case 3:
return false;
case 4:
return false;
}
}
}).on('changeDate', function (e) {
var from = $('#from-date').val();
var to = $('#to-date').val();
if (from !== to) {
$.ajax({
type: "GET",
url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),
dataType: "json"
})
.done(function (data) {
//var legth = data.chart.length;
$('#brandtable').empty();
var contents = $.parseJSON(data);
$.each(contents, function (key, values) {
$.each(values, function (k, v) {
$('#brandtable').append("<td><button class='btn btn-default' id=" + v.ID + ">" + v.BrandName + "</button></td>");
if (k % 9 === 0) {
if (k !==0) {
$('#brandtable').append("<tr></tr>");
}
}
});
});
});
};
});
});
Ok now, everything is fine, content was added successfully with button tag, but now i want click on button to get data from server just like above action, it is very strange that click event doesn't work, i don't know why? i did it in this way,
#foreach (var item in Model)
{
<text>
$("##item.ID").click(function () {
$.getJSON("#Url.Action("ReturnContentForSrpead", new { #ID = item.ID })", function (msg) {
var tags = BID.getParams.C32().tags;
var data = (msg.data || {}).wordgraph || [{ key: tags[0] }, { key: tags[1] }, { key: tags[2] }, { key: tags[3] }, { key: tags[4] }];
iDemand.drawBg().setData(data[lastTab]).drawCircle(BID.getColor(lastTab)).wordgraph = data;
});
});
</text>
}
i passed all instances from controller when i render page at very beginning, so that means all content already got, but only use jquery ajax to achieve kind of asynchronous. if you confuse with why i used Razor to render scripts, ok, i tried javascript as well, but got same result.
but one thing makes me shake was, when i run below code from console, it works fine.
$("##item.ID").click(function () {
console.log('clicked');
});
Do not render inline scripts like that. Include one script and add a class name to the dynamically added elements and store the items ID as a data- attribute, then use event delegation to handle the click event
In the datepickers .on function
var table = $('#brandtable'); // cache it
$.each(values, function (k, v) {
// Give each cell a class name and add the items ID as a data attribute
table .append("<td><button class='btn btn-default brand' data-id="v.ID>" + v.BrandName + "</button></td>");
Then use event delegation to handle the click event.
var url = '#Url.Action("ReturnContentForSrpead")';
table.on('click', '.brand', function() {
// Get the ID
var id = $(this).data('id');
$.getJSON(url, { ID: id }, function (msg) {
....
});
});
Side note: Its not clear what your nested .each() loops are trying to do and you are creating invalid html by adding <td> elements direct to the table. Best guess is that you want to add a new rows with 9 cells (and then start a new row) in which case it needs to be something like
$.each(values, function (k, v) {
if (k % 9 === 0) {
var row = $('</tr>');
table.append(row);
}
var button = $('</button>').addClass('btn btn-default brand').data('id', v.ID).text(v.BrandName);
var cell = $('</td>').append(button);
row.append(cell);
})
Recommend also that you change
url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),
to
url: '#Url.Action("DataChanged")',
data: { fromDate: from, toDate: to }, // you already have the values - no need to traverse the DOM again
You are binding click event on every item ID but the way you are getting id is not right. This $("##item.ID") will not find any element because this will bind click to an element whose id is #item.ID and there is no such element will this id. You need to change it like below. Concatenate "#" with each item id.
$("#"+#item.ID).click(function () {
//your code
})
I have a JQGrid.I need to take some Id to the OnClick function.In my scenario i wanted to get BasicId to the OnClick function.
MyCode
function grid() {
//JqGrid
$('#griddata').html('<table class="table" id="jqgrid"></table>')
$('#jqgrid').jqGrid({
url: '/Admin/GetBasicData/',
datatype: 'json',
mtype: 'GET',
//columns names
colNames: ['BasicId','Images'],
//columns model
colModel: [
{ name: 'BasicId', index: 'BasicId', resizable: false },
{
name: 'Images',
width: 120,
formatter: function () {
return "<button class='btn btn-warning btn-xs' onclick='OpenDialog()' style='margin-left:30%'>View</button>";
}
},
//Some Code here
Open Dialog Function
function OpenDialog(BasicId)
{
//Some code here
}
You can use onclick='OpenDialog.call(this, event)' instead of onclick='OpenDialog()'. You will have this inside of OpenDialog initialized to the clicked <button> and the event.target. Thus your code could be like the following
function OpenDialog (e) {
var rowid = $(this).closest("tr.jqgrow").attr("id"),
$grid = $(this).closest(".ui-jqgrid-btable"),
basicId = $grid.jqGrid("getCell", rowid, "BasicId");
// ...
e.stopPropagation();
}
One more option is even better: you don't need to specify any onclick. Instead of that you can use beforeSelectRow callback of jqGrid:
beforeSelectRow (rowid, e) {
var $td = $(e.target).closest("td"),
iCol = $.jgrid.getCellIndex($td[0]),
colModel = $(this).jqGrid("getGridParam", "colModel"),
basicId = $(this).jqGrid("getCell", rowid, "BasicId");
if (colModel[iCol].name === "Images") { // click in the column "Images"
// one can make additional test for
// if (e.target.nodeName.toUpperCase() === "button")
// to be sure that it was click to the button
// and not the click on another part of the column
OpenDialog(rowid);
return false; // don't select the row - optional
}
}
The main advantages of the last approach: one don't need to make any additional binding (every binding get memory resources and it take time). There are already exist on click handler in the grid and one can use it. It's enough to have one click handler because of event bubbling. The e.target provide us still full information about the clicked element.
Writing js event in your buttons html is not a good idea, its against 'un-obtrusive javasript' principle. You can instead add a click event on the entire grid in the render function and in the callback, filter out based on whether the button was clicked.
//not sure of the syntax of jqgrid, but roughly:
render: function(){
$('#jqgrid').unbind('click').on('click', function(){
if($(e.target).hasClass('btn-warning')){
var tr = $(e.target).parent('tr');
//retrieve the basicId from 'tr'
OpenDialog(/*pass the basicId*/)
}
})
}
I am looking for a recommendation on the best way to organised my code. I have a lot of jQuery event handle which are used for:
dropdown menus, tabs etc
form validation
$.ajax get requests for dynamic form <options>'s
$.ajax post requests for form submitting.
An MVC framework like backbonejs seems like overkill but my current code isn't maintainable and will continue to get worse unless i give it some kind of structure.
$('#detailsform').find('.field').on('click','.save',function(){
var input = $(this).siblings().find('input');
input.attr('type','hidden');
$(this).siblings().find('p').text(input.val());
$(this).text('Change').addClass('change').removeClass('save');
url = null; //query str
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
//next event listener
//next event listener
//next event listener
//next event listener
that is one of many event listeners. Any suggestions on how to organise this?
I would use the following structure. Simply add more objects in the eventHandlers array for each element you need. This could even be done programatically.
(function() {
var Site = {
init: function() {
this.bindEventHandlers();
},
bindEventHandlers: function() {
for (var i=0; i<this.eventHandlers.length; i++) {
this.bindEvent(this.eventHandlers[i]);
}
},
bindEvent: function(e) {
e.$el.on(e.event, e.handler);
console.log('Bound ' + e.event + ' handler for', e.$el);
},
eventHandlers: [
{
$el: $('#element1'),
event: "click",
handler: function() { console.log('Clicked',$(this)) }
},
{
$el: $('#element2'),
event: "click",
handler: function() { console.log('Clicked',$(this)) }
}
]
};
Site.init();
})();
Fiddle here: http://jsfiddle.net/chrispickford/LQr2B/