I am trying to bind a child table with a parent table. I am not able to figure out how this can be done when the data for the child table is coming through an AJAX call which then creates a dynamic table.
I have followed this
Below is my code.
$('#myTable tbody).on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format()).show();
tr.addClass('shown');
}
});
function format() {
$.ajax({
type: 'GET',
url: '#Url.Action("MyFunction", "Home")',
data: { "Id": MyId },
dataType: "json",
async: false,
success: function (data) {
var list = data;
$.each(list, function (index, item) {
return '<table>.......<table />';
//i need to loop across the list and create a dynamic table with tr and td
});
},
error: function (result) {
var error = JSON.stringify(result);
throw "Error...";
}
});
}
$('#myTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
format(row.child); // create new if not exist
tr.addClass('shown');
}
});
and then the format() will be
function format(callback) {
$.ajax({
....
//async: false, you can use async
success: function (data) {
var list = data;
var html = '';
$.each(list, function (index, item) {
...
//create <tr> <td> with loop
html= '<tr><td>.......</tr>';
});
callback($('<table>' + html + '</table>')).show();
},
...
});
}
demo here jsfiddle
Related
I have a leaflet map with the boundaries of Europe countries. When the user clicks on a feature I get the name of Country by a field in geojson file.
I also have a datatable with data from database and I have a function on row click.
How I can perform a click on datatable row from leaflet feature click?
The problem: on feature click -> execute a function
With the below code I get Feature Name and search on datatable
layer_europe_with_data_0.on('click', function(e) {
var dd = e.layer.feature.properties.NAME_ENGL
var tbldump = $('#europetbl').DataTable();
tbldump.search(dd).draw();
}
One way was that I found the search option on datatable, so I can search on datatable for the row. But I can perform the click on.
The function on row click
$('#europetbl tbody').on('click', 'tr', function () {
// bla bla bla
}
I want to do this:
layer_europe_with_data_0.on('click', function(e) {
do this $('#europetbl tbody').on('click', 'tr', function () {
}
code for row click
$('#europetbl tbody').on('click', 'tr', function () {
var tbl = $('#europetbl').DataTable();
var dt = tbl.row( this ).data();
mymap.setView([dt[4], dt[3]],6)
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
tbl.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
$("#fetchtbl tbody").html("");
var id = dt[0];
idforcountrystats = id;
localStorage.setItem("idforstats", idforcountrystats);
$.ajax({
url: "fetchdata.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" data-id="'+ item.fetID+'"
onclick="QuickView(this)"></td><td>' + item.Fua_name + '</td></tr>' ;
});
$('#fetchtbl tbody').append(trHTML);
}
}
})
})
How can I get each column in row without using .find('td:eq(0)')? I need another way to get each column.
$(document).on('click', '.delete_librarian', function()
{
var librarianDataRow=$(this).closest('tr');
var librarianId=parseInt(librarianDataRow.find('td:eq(0)').text());
var librarianName=librarianDataRow.find('td:eq(1)').text();
$('#confirm-model-body').text("Are you sure you want to delete "+librarianName+" data");
$('#confirm-modal').modal({backdrop: 'static'});
$('#confirm-model-yes-button').click(function () {
$.ajax({
url: "/api/admin/librarian",
type: "DELETE",
dataType: "json",
data: JSON.stringify({id:librarianId}),
success:function (data) {
if(data.success == true)
{
window.location.reload();
}
else
{
alert(data.message);
}
}
});
});
});
You could use vanilla JS instead if you don't want to use jQuery methods for whatever reason:
$(document).on('click', '.delete_librarian', function() {
var librarianDataRow = this.closest('tr');
var librarianId = Number(librarianDataRow.children[0].textContent);
var librarianName = librarianDataRow.children[1].textContent;
// ...
Could also use
$(document).on('click', '.delete_librarian', function() {
var librarianDataRow = this.closest('tr');
var librarianId = Number(librarianDataRow.cells[0].textContent);
var librarianName = librarianDataRow.cells[1].textContent;
// ...
I have written a code in Javascript in which I have attached an input type submit to a form. On form submit the listener gets called.
The problem is that on when I click the button once, one ajax call occurs. When I click it again two calls occur while only one call should occur on each click. Similarly on clicking 3 times 3 calls occur and so on...(the calls get increasing). If I refresh the page then the number gets reset. I have tried everything but I had no luck. If anyone found out what is wrong here it would be awesome. Thanks in advance.
javascript code:
$('input.create-discounts-quotations').click(function () {
var discount_quotation_type = $('input.quotation-discount-type').val();
if (discount_quotation_type == "value") {
var total = $('input.discount-input-quotation').val();
var discounted_price = product_price - total;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "percentage") {
var total = $('input.discount-input-quotation').val();
var temp_first = product_price;
var temp1 = total / 100;
var temp2 = temp1 * product_price;
var discounted_price = product_price - temp2;
$('#final_discounted_amount').val(discounted_price);
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.quotation-response-discounts');
$(td).each(function () {
$(this).html(total);
});
});
$("table.product-response-table tr").each(function () {
var row = $(this).index() + 1;
var td = $(this).find('td.product_final_price_discounted');
$(td).each(function () {
$(this).html(discounted_price);
});
});
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
}
if (discount_quotation_type == "not_selected") {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-danger">Discount Method Not Selected</div>');
return false;
}
// return false;
});
That happen because every time you click your code will reattach the submit event so it will be duplicated in every click.
You should never attach the events inside other events, please put the submit event outside of the click event and the code should work, example :
var form1 = $('form#quotation_discount_update_form');
form1.on("submit", function (e) {
var form_data1 = form1.serialize();
$.ajax({
type: 'POST',
url: form1.attr('action'),
data: form_data1,
dataType: "json",
success: function (data) {
$('.quotation-discount-status-update').empty();
$('.quotation-discount-status-update').append('<div class="alert alert-success">Discount Added</div>');
}
});
e.preventDefault();
});
Else you have to remove the event handler every time using .off(), like :
form1.off("submit").on("submit", function (e) {
I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});
FOUND THE PROBLEM:
Just needed to replace row.replaceWith with row.parent().parent().replaceWith().
I'm trying to update a WebGrid row with JQuery after I've clicked a submit button in a modal dialog, but the updated data just append the last column, not the whole row as I want.
Let's say I want the table to look like this after the update:
ID - Name - Phone number
But with my code it looks like this after the update:
ID - Name - ID - Name - Phone number
as it just replaces the last column with a new table within the last column with the updated data.
I'm getting the correct data as output, but in the wrong place in the row.
Please help! :)
Here is the Javascript code:
$(function () {
$("#edit-event-dialog").dialog({
resizable: false,
height: 300,
modal: true,
autoOpen: false,
open: function (event, ui) {
var objectid = $(this).data('id');
$('#edit-event-dialog').load("/Events/CreateEditPartial", { id: objectid });
},
buttons: {
"Save": function () {
var ai = {
EventID: $(this).data('id'),
Name: $("#Name").val(),
Phone: $("#Phone").val()
};
var json = $.toJSON(ai);
var row = $(this).data('row');
$.ajax({
url: $(this).data('url'),
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var grid = $(".pretty-table");
row.replaceWith('<tr><td>' + data.ev.EventID + '</td><td>' +
data.ev.Name + '</td><td>' + data.ev.Phone + '</td></tr>');
},
error: function (data) {
var data = data;
alert("Error");
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this);
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row)
.dialog('open');
event.stopPropagation();
return true;
});
You have set row to $(this) which is your case represents $("#event-edit-btn") ( btw i suggest using classes as identifiers, but it's not a problem ). Later on you replace your actual button with the new <tr> set but what you actually need to do is traverse to the tr parent of that button and replace it.
Change your live handler to:
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this).closest('tr'); //or use some #id or .class assigned to that element
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row )
.dialog('open');
event.stopPropagation();
return true;
});