Deleting multiple rows of a table with Jquery and ajax - javascript

I want to be able to delete checkbox-selected rows but when I click on "Delete Selected", both the table on the web page and MySQL database stay unchanged. How do I get the selected rows from both the web page and the database to be deleted?
Edit: I'm now able to delete the rows but only the first row, despite selecting more than one checkbox, or selecting another checkbox not on the first row. Also, if I want to delete another entry, I will have to first refresh the page before deleting another one.
datatable.php
<div class="row well">
<a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>
<script type="text/javascript">
$(document).ready(function($)
{
function create_html_table (tbl_data) {
tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';
tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';
tbl +='<tbody>';
$.each(tbl_data, function(index, val)
{
var row_id = val['row_id'];
//loop through ajax row data
tbl +='<tr id="row" row_id="'+row_id+'">';
tbl +='<td><input type="checkbox" class="sub_chk"></td>';
tbl +='<td>'+(index + 1)+'</td>';
tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
// More data
tbl +='</tr>';
});
tbl +='</tbody>';
tbl +='</table>';
}
var ajax_url = "<?php echo APPURL;?>/ajax.php" ;
// Multi-select
$(document).on("click","#master", function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
var ele_this = $('#row') ;
var row_id = ele_this.attr('row_id');
var allVals = [];
$(".sub_chk:checked").each(function()
{
allVals.push(row_id);
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var data_obj=
{
call_type:'delete_row_entry',
row_id:row_id,
};
ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
}
else if(d1.status == "success")
{
ele_this.closest('tr').css('background','red').slideUp('slow');
}
});
}
});
});
</script>
ajax.php
//--->Delete row entry > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")
{
$row_id = app_db()->CleanDBData($_POST['row_id']);
$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0)
{
//found a row to be deleted
$strTableName = "data";
$array_where = array('row_id' => $row_id);
//Call it like this:
app_db()->Delete($strTableName,$array_where);
echo json_encode(array(
'status' => 'success',
'msg' => 'deleted entry',
));
die();
}
}
//--->Delete row entry > end
I've seen other similar SO questions like this one but I don't think it is applicable to my code.
My output:

To achieve what you want, you have to select the good elements the right way. For example, an HTML id must be unique, so giving all your elements the same id="row" won't work. Using your class will be enough. Then you have to consider that each will execute the function separately for all your selected elements, so that if you want to do things for each element, all the code must be inside.
I optimized a little your code by getting rid of allVals variable, if its only goal is to test if rows have been selected, you can directly test .length on your selection. I renamed variables so that it's more clear which is what.
Also it's not very clear in the question if the "Please wait....deleting your entry" text should appear in the button or in each row, i assumed it was in the button, and it will help you differentiate all elements from how they are selected.
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
//'click' is called on the button, so 'this' here will be the button
var button = $(this) ;
var checked_checkboxes = $(".sub_chk:checked");
if(checked_checkboxes.length <=0)
{
alert("Please select row.");
}
else {
button.html('<p class="bg-warning">Please wait....deleting your entry</p>');
//next code will be executed for each checkbox selected:
checked_checkboxes.each(function(){
var checkbox = $(this);
var row_id = checkbox.attr('row_id');
var data_obj=
{
call_type: 'delete_row_entry',
row_id: row_id,
};
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
//you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
}
else if(d1.status == "success")
{
checkbox.closest('tr').css('background','red').slideUp('slow');
}
});
});
}
});

Related

How to delete a data based on a button

What i accomplished now is when i clicked "add to my stay" button, it will display the name and price data and it will automatically switch to remove button and then click again for another addon to display another name and price data. Now if i press the remove button of the 1st "add to my stay" it will delete both data on each button that i pressed adding. My goal is to remove a data based on its button ID like i want to remove The data on my 1st "Add to my stay" button it will only delete the 1st data
MY JS CODE FOR REMOVE it is outside the (document).ready
function Remove(id) {
console.log("call remove");
$('li.price').each(function (index, object) {
var id2 = $(object).data('addon-id');
console.log(id);
if (id2 === id2) {
$(object).remove();
}
});
$(this).addClass('is-hidden');
$('.addons[data-addon-id="' + id + '"]').removeClass('is-hidden');
}
My code for getting the data on add to my stay button
$(document).ready(function(){
$(".addons").on("click", function(event) {
event.preventDefault();
var $this = $(this);
var id = $(this).data('addon-id');
name = $(this).data('name');
price = $(this).data('price');
console.log(id);
$(this).addClass('is-hidden');
$('.removebtn[data-addon-id="' + id + '"]').removeClass('is-hidden');
if(id != '')
{
$.ajax(
{
type:"POST",
url : "Pages/addonajax",
data:{id:id,
name:name,
price:price},
success:function(data)
{
console.dir(data);
if (data) {
var item = $('<li data-itemprice="'+price+'" class = "price">'+name+' : '+price+'</li>');
$("#test1").append(item);
Total();
}
else {
}
}
});
}
});
My code on the button
<button data-name = "Airport Transfer" data-price = "4300" class="addons addon-btn trans_200" data-addon-id ="1">ADD TO MY STAY</button>
<button class="removebtn remove-btn is-hidden trans_200" data-addon-id ="1" onclick="Remove(1)" value="Remove">Remove</button>
Your problem is here:
if (id2 === id2) {
$(object).remove();
}
id2 will always be equal to itself, and therefore you will always call $(object).remove();
You need to compare id2 to id
if (id2 === id) {
$(object).remove();
}
EDIT
You also have a problem in your loop of the list items:
var id2 = $(object).data('addon-id');
Your list items do not have a data-addon-id attribute
Put a data-addon-id on the list item when you create it:
var item = $('<li data-addon-id="' + id + '" data-itemprice="'+price+'" class = "price">'+name+' : '+price+'</li>');
$("#test1").append(item);

How to pass values of selected checkboxes from multiple pages in Data Table

I have records in bootstrap data table which has pagination and each record will have a checkbox. Let say when I click some checkboxes in page 1 and some checkboxes in page 2, the form will only pass value of checkbox in page 2. How can I retrieve the checkbox values from page 1?Any help is much appreciated.
var checkboxes = $("input[type='checkbox']"),
btn = $("#btnCutoff");
//structure of table
var table = $('#table').DataTable({
"bLengthChange": false,
"pageLength": 5,
"bFilter": false
});
//disable button when no records are selected
btn.attr("disabled","disabled");
checkboxes.on('click', function(event) {
if($(this).prop('checked')){
btn.removeAttr('disabled');
} else {
btn.attr("disabled",!checkboxes.is(":checked"));
}
});
$("#table tbody").on("click",".clickable-row", function (event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
when clicks button, it will go to a javascript function
function doEnquiry(){
var f = document.frm;
f.method = "POST";
f.action = "test.jsp";
f.target = "_self";
f.submit();
}
and I want to assign the checkbox values to here
String curr[] = request.getParameterValues("chkTest");
Can anyone help me?
On every checkbox click if the checkbox is checked create a hidden field to store its value.You can rely on the hidden field values to capture all the checkbox values you want and can easily access them on the server side instead.
checkboxes.on('click', function(event) {
if($(this).prop('checked')){
btn.removeAttr('disabled');
$('form').append('<input type="hidden" name="fieldname" value="'+this.value+'" />');
} else {
btn.attr("disabled",!checkboxes.is(":checked"));
}
});
Jquery code
$(document).ready(function() {
$('#viewlist').DataTable();
$("#button").click(function() {
var chcklist = new Array();
var oTable = $('#viewlist').dataTable();
var rowcollection = oTable.$("#emp_name:checked", {"page": "all"});
rowcollection.each(function(index,elem) {
chcklist.push($(elem).val());
});
$.post(
"../accounts/updateSalaryHold.jsp",
{list: chcklist},
function (values) { }
);
});
});
jsp page Code
String[] arrayVal = request.getParameterValues("list[]");

JQuery display checkboxed table row data

So I know there are a few posts about this but I haven't found them to helpful so I'm hoping this will shed new light on my problem.
I'm trying to to get data from a check-boxed row in a HTML table. At the moment I only want to display it on a windows.alert or in the Visual Studio console. But eventually I'm going to post the data to a database.
My code:
$(document).ready(function () {
$('#button').click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please select at least one checkbox");
}
else {
$.post('http://localhost/Dynamic/?Insert');
}
});
});
I've tried alert($(this).text()) but that just appears empty.
Help would be appreciated.
If it helps this is how I populate the table:
var tableName = 'table1'
$.ajax({
url: 'http://localhost/Dynamic?prod=' + tableName,
dataType: 'Json',
success: function (Results) {
$.each(Results, function () {
var row = "";
for (i = 0; i < this.length; i++) {
var input = '<td>' + this[i] + '</td>';
row = row + input;
}
$('#table1 tbody:last-child').append('<tr>' + row + '<td> <input class="checkBox" type="checkbox" id="count"/> </td></tr>');
});
}
});
As you can see the table is populated dynamically so it can be populated by different tables.
your selector is wrong. $(':checkbox:checked') should be $('.checkbox:checked').
maybe try to change to different class name.
$('.mycheckbox:checked').each(function (i) {
id[i] = $(this).val();
});
I've gotten it to work, I created a global array and added all the values to that. I then created a counter and set each checkbox's ID to the counters value. I then increment the counter before looping back around to sort with the next row of data.
Then When I want to choose data. I check the checkbox's of the data. Press the button then I get the Id's of each of the checkbox's. I then put the checkbox id into the array to get the value before adding it to an array which I then post.

how to find duplicate dropdowns in a table using jquery?

There is a table which contains an user dropdown per row. Needs to prevent to select duplicate users in the table.
I have written js function for it.But it's not accomplish the requirements.
HTML
Javascript function
function checkDuplicateUserId(obj){
var user_id=$("#"+obj.id+" option:selected").val();
$('tbody#data tr select').each(function (i, row) {
if ($('tbody#data tr select').find('option[value="' + $(this).val() + '"]').size() > 1) {
alert();
}
});
}
function checkAlreadySelected(obj){
checkDuplicateUserId(obj);
var num = parseInt($(obj).attr('num'));
var user_id=$("#"+obj.id+" option:selected").val();
var next_user_id=$("#user_id_"+eval(num+1)+" option:selected").val();
if(user_id && typeof next_user_id == 'undefined'){
var row = updateSrNo(num);
$("#data").append(row);
}
}
Why this alert() not prompted while i choose the duplicate user from the table?

Dynamic Query Builder

I am creating a custom MySQL database query UI. Inside this UI I have a Query Builder interface that I would like to dynamically append query properties based on the user selections in order to create a dynamic query. Please see the below picture for a visual description
From the picture above I would like to append CHARACTER_SET after the FROM and append as asterisk when ALL is selected from the table and so forth with the key being the positions where I place the generated variables.
How can I achieve this with JQuery?
My JavaScript
Selecting a Table
$(document).on("change", ".tbl_list", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var db = window.sessionStorage.getItem("db");
$.ajax({
type: "POST",
url: "ajax2.php",
data: {
tbl: tbl,
db: db
},
success: function (html) {
console.log(html);
$("#tblField").html(html).show();
}
});
});
Selecting All option
$(document).on("click", ".tblall", function () {
if (this.checked) {
// Iterate each checkbox
$('.tblst').each(function () {
this.checked = true;
});
} else {
$('.tblst').each(function () {
this.checked = false;
});
}
});
EDIT
As requested HTML for my DIVs
Table Selector
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
?>
<input type="checkbox" name="tbl[]" class="tbl_list"
value="<?php echo $row [0]; ?>" />
<?php echo $row [0]; ?>
<br>
Query Builder
<div id="qryDisplay">
<fieldset>
<legend> Query Builder</legend>
<div id="qryView">
<p>SELECT FROM</p>
</div>
</fieldset>
</div>
What I have tried so far
Using .append I can add data to the end of the paragraph so this would be ideal for my Table name. However its a function and i'm not sure how I would implement the code below into my select table function.
$("#qryView > p").append(" " tblName);
Anyway, not considering the logic behind the selection of multiple tables my approach would be to store selections in hidden input fields and at the end construct from the hidden fields the query.
<input type="hidden" value="" name="hiddenTables" id="hiddenTables" />
fill field according to selections in your function from above:
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
if($('#hiddenTables').val() == ""){
$('#hiddenTables').val($(this).val());
}else{
$('#hiddenTables').val($('#hiddenTables').val()+','+$(this).val());
}
});
At the end create your query:
// hidden field for field selection, same as above.
var fieldselection = '*';
if($('#hiddenFieldselection').val() != ""){
fieldselection = $('#hiddenFieldselection').val();
}
$("#qryView > p").html("SELECT " + fieldselection + " FROM " + $('#hiddenTables').val());
This needs to be adjusted the way you need it of course and I haven't tested any of this... So that's up to you :-)

Categories