How to delete a data based on a button - javascript

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);

Related

Get the ID in row that has radio button checked [duplicate]

This question already has answers here:
Getting values of elements in same row when button is clicked, one button per row
(2 answers)
Closed last year.
I have this function which creates a table in a modal popup and the table gets populated from data in an array passed in from an ajax call. Now on the click of a button in the modal popup I need to get the value of item.TimedPathwayID that has its radio button checked and add it to a hidden field.
function PopulateTimedPathwaysTable(tblData) {
var tbody = $('#tblTimedPathways tbody');
$.map(tblData.d, function (item) {
tr = $('<tr></tr>');
tr.append('<td class="pathwayID">' + item.TimedPathwayID + '</td>');
tr.append('<td>' + item.TimedPathwayName + '</td>');
tr.append('<td><input type="radio" class="radioSelection" name="timedPathwaySelection"" />');
tbody.append(tr);
});
$('input[name=timedPathwaySelection]:first').attr('checked', true);}
}
I've been fiddling with this kind of thing but with no joy and the radio button in the first row is checked by default so this can't really be tied to a click event if a user just accepts the default without clicking. So how can I do it please?
$('body').on('click', '.radioSelection', function () {
var $tbl = $('#tblTimedPathways tbody');
var $dataRow = $tbl.closest('tr');
var id = $dataRow.find('td').eq(0).html();
});
.closest goes up the html tree, so tbody.closest(tr) is unlikely to be what you want.
you need to then go back down to the cell that contains the data you want.
let $this = $(this); //this is the radio button
let id = $this.closest("tr").find("td.pathwayID").text();
I would also echo that I would generally add the id as an attribute to the row to remove the necessity of the find later.
//sample data
let data = {
d: [{
TimedPathwayID: 1,
TimedPathwayName: "test"
},
{
TimedPathwayID: 2,
TimedPathwayName: "test"
},
{
TimedPathwayID: 3,
TimedPathwayName: "test"
}
]
};
function PopulateTimedPathwaysTable(tblData) {
var tbody = $('#tblTimedPathways tbody');
$.map(tblData.d, function(item) {
tr = $('<tr></tr>');
tr.append('<td class="pathwayID">' + item.TimedPathwayID + '</td>');
tr.append('<td>' + item.TimedPathwayName + '</td>');
tr.append('<td><input type="radio" class="radioSelection" name="timedPathwaySelection"" />');
tbody.append(tr);
});
$('input[name=timedPathwaySelection]:first').attr('checked', true);
}
//populate it
PopulateTimedPathwaysTable(data);
$('body').on('click', '.radioSelection', function () {
let $this = $(this); //this is the radio button
//console.log($this);
let id = $this.closest("tr").find("td.pathwayID").text();
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblTimedPathways">
<tbody>
</tbody>
</table>

Jquery how to pass value id from one event handler to another

I have an add-row button. On its click I am adding a row into my datatable.
$('.add-row').on('click', function() {
id = 0;
name = $('#name').val();
email = $('#email').val();
cno = $('#cno').val();
bdy = $('#bday').val();
t.row.add([
name,
email,
cno,
bdy,
'<button class ="btn btn-danger del">Delete</button>' + '' + '<button class="btn btn-warning upd" data-id="'+$('#example').DataTable().rows().count()+'">Edit</button>'
]).draw(false);
$("#name").val('');
$("#email").val('');
$("#cno").val('');
$("#bday").val('');
});
In the above code, I am using data-id and adding row id to it. On my edit button click I am getting the data-id value.
$("body").on("click", ".upd", function(e) {
const id = $(this).attr("data-id");
console.log(id);
// Prevent event propagation
e.stopPropagation();
var $row = $(this).closest('tr');
var data = t.row($row).data();
//alert('Edit ' + data[0]);
name = data[0];
email = data[1];
cno = data[2];
bdy = data[3];
console.log(name);
console.log(email);
console.log(cno);
console.log(bdy);
$("#name1").val(name);
$("#email1").val(email);
$("#cno1").val(cno);
$("#dob1").val(bdy);
$("#myModal").modal('show');
});
The above code takes input data from modal. In my modal I have a save button having id btnsubmit. Now on this button click, I want to pass my data-id.
$("#btnsubmit").on('click',function () {//in this event i want to pass the `data-id`
var new_name = $("#name1").val();
var new_email = $("#email1").val();
var new_cno = $("#cno1").val();
var new_dob = $("#dob1").val();
$("#myModal").modal("hide");
});
How can I pass the value of data-id in it?
Any help would be highly appreciated.
you could stock your data in html modal like this:
$("#myModal").data('id', id);
and use:
var id = $("#myModal").data('id');

Deleting multiple rows of a table with Jquery and ajax

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');
}
});
});
}
});

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

Remove button in table row

I am working on a shopping cart application. I have used jQuery to fetch the items and display it in table format. Each item table contains a remove button to remove it from the cart. I have used the click function on the table to remove the item. But if I click on the qty field also the table is removed because its inside the table. I want the table to be removed when I click the remove button inside the table.
$(document).ready(function(){
$(".add_cart").click(function(){
var id = this.id;
$(this).prop("disabled",true);
$.get("cart.php",{
"id":id
},function(data){
$("#sam").append("<table id='"+id+"' class='tables'><tr><td>"+data+"</td><td><input class='remove' id='"+id+"' type='button' value='Remove'></td></tr></table><br>");
$(".remove").click(function(){
$(table.tables).remove();
$("#"+id).prop("disabled",false);
});
});
});
});
use this:
$("table.tables").remove();
Try
$(document).ready(function () {
$(".add_cart").click(function () {
var id = this.id;
$(this).prop("disabled", true);
$.get("cart.php", {
"id": id
}, function (data) {
$("#sam").append("<table id='" + id + "' class='tables'><tr><td>" + data + "</td><td><input class='remove' type='button' value='Remove'></td></tr></table><br>");
});
});
//use event delegation
$("#sam").on('click', '.remove', function () {
//get the table which contains the button
var $tbl = $(this).closest('tr').remove();
//get the id of the table instead of the id variable
$("#" + $tbl.attr('id')).prop("disabled", false);
});
});
Note that the Id of an element must be unique, you have a table and a button with the same id... remove the id from the button

Categories