I have a html table that has a content came from a database by using ajax and php.
When i try to add a new row manually by filling all the inputs and click save button it will add the data to the table.
My problem is when i try to delete the newly added rows and click the delete button on that specific row it doesn't delete. But when i try to delete the rows that came from the database it is deleted from the html table.
script:
$.ajax({
url: 'process.php',
type: 'post',
data: {tag: 'getData'},
dataType: 'json',
success: function(data){
if(data.success){
$("#myTable2 tbody").empty();
$.each(data, function(index, record){
if($.isNumeric(index)){
var row = $("<tr />");
$("<td />").text(record.name).appendTo(row);
$("<td />").text(record.age).appendTo(row);
$("<td />").text(record.gender).appendTo(row);
$("<td />").html(record.action).appendTo(row);
row.appendTo("#myTable2 tbody");
}
})
}
var oTable = $('#myTable2').DataTable();
$("#myTable2 tbody .dltRow").bind( 'click', function(event) {
var row = $(this).closest('tr').get(0);
oTable.row(row).remove().draw();
oTable.row($(this).closest('tr')).remove().draw();
$(this).parent().parent().closest('tr').remove();
oTable.fnDeleteRow(oTable.fnGetPosition(row));
});
$('#Save2').on( 'click', function () {
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<center><button type='button' class='btn btn-default dltRow'><i class='glyphicon glyphicon-trash'></i></button></center>"
];
oTable.row.add(data).draw();
});
}
});
use event delegation to attach events to dynamically added delete buttons.
$("#myTable2 tbody").on( 'click','.dltRow', function(event) {
var row = $(this).closest('tr').get(0);
oTable.row(row).remove().draw();
oTable.row($(this).closest('tr')).remove().draw();
$(this).parent().parent().closest('tr').remove();
oTable.fnDeleteRow(oTable.fnGetPosition(row));
});
Related
I have a table with rows. In each row is a button that is specific to that row of data through the value of the data's id.
When a button in a specific row is clicked it fires the AJAX function 'options'. If that is successful then I want to append the data from $newElement to the row in which that button is located. The row is not always the same however so I cant just give it a tr#.
In the code below I have the append working with that data I want but it appends it to every row, not limited to the specific row and that button's id. What am I doing wrong?
AJAX/jQuery where I am appending the data from $newElement but am having trouble binding the id from the button. As a result it adds the data from $newElement to every row instead of ONLY the row in which I clicked the button.
function options(id){
jQuery.ajax({
type: 'post',url: my_ajax.ajax_url,
data: {action: 'options_function',cid : id_In},
success: function (data) {
var $id = id
var $newElement=jQuery("<tr>",
{id:'ideal_option'+id,html:data})
jQuery('#list-table tr').append($newElement)}
});
}
The button and its initial table are generated with a combo of jQuery and HTML. This function is launched on page load. :
function Pop(){ ?>
<script>
jQuery('document').ready(function(){
jQuery.ajax({ data: {action: 'list_ct'},
type: 'post', url: my_ajax.ajax_url,dataType: 'JSON', success: function(data) {
var lnth = data.length-1;jQuery.each( data, function( i, val ) {
console.log(val);
jQuery('<tr><td>'+val.Customer_FName+' '+val.Customer_LName+'<br></td><td class="tdid_'+val.id+'">'+val.Status+'</td><td><button id="options" href="javascript:void(0)" class="button" onclick="options('+val.id+')" data-id="'+val.id+'"></button></td></tr>');
});
}
});
});
</script>
<table id='list-header'>
<th>Name</th>
<tbody id='list-table'>
</tbody>
</table>
<?php
}
I'm building up a table in the View from clicking items in a dropdown menu; I already have a script that does this.
It is also set up so that when an item in the table is clicked, it is removed by the line $(this).parent().remove();
The above two features work
What I need help with is using Ajax to remove the item from the DB as well as just from the table in the View. I already have the controller set up to do this.
My desire is to pass in the id of a removed row to the Ajax section
//Function to append each item clicked in dropdown box to table
$("#subjectlist")
.change(function () {
$("select option:selected").each(function () {
console.log($("select option:selected"));
//the below line of code is setting the id to the
//string: "this.value" and not the number as desired.
//I have confirmed this.value is a number by console
//logging it
$('#overview').append("<tr id='this.value'><td>" +
$(this).text() + "</td><td id=" + this.value + ">" /*+
"X"*/ + "</td></tr>");
});
})
.trigger("change");
//Function to remove fields from table
$("#overview").on('click', 'td', function () {
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})
//If anyone wants to see ,below is the table and the form tag helper
using mvc core's ajax helpers to add and display items items to the
table with Ajax
<select asp-for="SubjectAreasOfProgramme"
asp-items="Model.SubjectAreasForDropdown"></select>
<table id="overview" class="table table-sm table-borderless">
#foreach (var item in Model.SubjectAreasOfProgramme)
{
<tr><td>#item</td><td id="Remove">X</td></tr>
}
</table>
In your click function you have to get the Id value before sending it the database via ajax.
$("#overview").on('click', 'td', function () {
var item = $(this).parent().find("td").eq(2).html(); // replace 2 with whatever cell that holds id value
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})
I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I'm creating a table with an Ajax Query on a modal hide event with this code.
$('#modalarticulos').on('hidden.bs.modal', function () {;
sel_articulos = $("input[name='check_art']:checked").map(function ()
{
return this.value;
}).get();
console.log(sel_articulos);
$("#sel_articulos tbody").empty();
ii =0;
var tbody = $('#sel_articulos tbody');
$.each(sel_articulos, function(ii, sel_articulo) {
var tr = $("<tr id=artrow["+ii+"]>");
$.ajax({
type: 'POST',
url: "<?php echo $_SERVER_ADDR . PUBLIC_PATH .'presupuestos/buscart/'; ?>",
data: { 'id':sel_articulos[ii]},
dataType: "json",
success: function(response) {
$("<td id='id["+ii+"]'>").html(response["id"]).appendTo(tr);
$("<td id='tipart["+ii+"]'>").html(response["tipart"]).appendTo(tr);
$("<td id='codart["+ii+"]'>").html(response["codart"]).appendTo(tr);
$("<td id='desart["+ii+"]'>").html(response["desart"]).appendTo(tr);
$("<td id='canart["+ii+"]'><input type='number' id='cantidad["+ii+"]' min='0' max='999' step='1' class='input-mini text-right cantidart' value='1'>").appendTo(tr);
$("<td id='precio["+ii+"]'>").html(response["precio"]).appendTo(tr);
$("<td id='subtot["+ii+"]'>").html("<label id='subtotal["+ii+"]' class='text-success subtotal'>"+response["precio"]).appendTo(tr);
tbody.append(tr);
},
error: function() {
alert('Error occurs!');
}
});
});
$('#sel_articulos > tbody').after(<tr><td></td><td></td><td></td><td></td><td><label class='subtotalg'>SUB-TOTAL</label></td><td></td><td><label id='subtotalsi' class='text-success subtotalg'>Subtotal</label></td></tr>;
})
question 1 the problem that i am facing is that i need the last row (the one being added after, the body) to be inside the body itself, now it is being created outside it and by consequence its not being cleared by the:
$("#sel_articulos tbody").empty();
Question 2 : in addition to that i would like to know if there is another way of arranging the creation of that table to make it more efficient. thank you.
$.after adds an element after the selected element. You need $.append which adds an element inside the selected element.
Do this:
$('#sel_articulos > tbody').append(<tr><td></td><td></td><td></td><td></td><td><label class='subtotalg'>SUB-TOTAL</label></td><td></td><td><label id='subtotalsi' class='text-success subtotalg'>Subtotal</label></td></tr>;
UPDATE
As per your comment, you need to add it after the rows are added. Just check if you're adding the last row first.
$.each(sel_articulos, function(ii, sel_articulo) {
$.ajax({
type: 'POST',
url: "<?php echo $_SERVER_ADDR . PUBLIC_PATH .'presupuestos/buscart/'; ?>",
data: { 'id':sel_articulos[ii]},
dataType: "json",
success: function(response) {
$("<td id='id["+ii+"]'>").html(response["id"]).appendTo(tr);
$("<td id='tipart["+ii+"]'>").html(response["tipart"]).appendTo(tr);
$("<td id='codart["+ii+"]'>").html(response["codart"]).appendTo(tr);
$("<td id='desart["+ii+"]'>").html(response["desart"]).appendTo(tr);
$("<td id='canart["+ii+"]'><input type='number' id='cantidad["+ii+"]' min='0' max='999' step='1' class='input-mini text-right cantidart' value='1'>").appendTo(tr);
$("<td id='precio["+ii+"]'>").html(response["precio"]).appendTo(tr);
$("<td id='subtot["+ii+"]'>").html("<label id='subtotal["+ii+"]' class='text-success subtotal'>"+response["precio"]).appendTo(tr);
tbody.append(tr);
// Check if added last row
if(ii == sel_articulos.length - 1){
$('#sel_articulos > tbody').append(<tr><td></td><td></td><td></td><td></td><td><label class='subtotalg'>SUB-TOTAL</label></td><td></td><td><label id='subtotalsi' class='text-success subtotalg'>Subtotal</label></td></tr>;
}
},
error: function() {
alert('Error occurs!');
}
});
});
However I would do what #Scottie said in the comments and get all the table data in one request, rather than one for each row. That would make this a lot easier because you could just append it after all the other ones have been appended.
You can use Deferred (and Promise) to manage it better, and indeed the ajax in jQuery would return a Promise like interface, so you can try:
var data = {};
var promise = $ajax.({
...
success: function (response) {
// Collect your data here
data['id'] = response['id'];
....
// This means success and the done callbacks in the deferred will be executed.
}
...
});
// The done call back will be executed after your ajax success callback is called
promise.done(function () {
// now use your data to create a table
...
});
Learn more about jQuery promise and defer:
https://api.jquery.com/promise/
https://api.jquery.com/category/deferred-object/