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>
Related
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');
}
});
});
}
});
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.
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
I want to give an id to each row in HTML, and when I enter that value into textbox, I want jquery to delete that row.
I have built this fiddle
http://jsfiddle.net/vYAq9/3/
$(document).ready(function(){
$("#addbutton").click(function(){
var uniqueid = $("#textbox1").val();
var text = $("#textbox2").val();
$("<tr><td>row content</td></tr>").val(uniqueid).html(text).appendTo("#table1");
});
$("#removebutton").click(function(){
var uniqueid = $("#textbox1").val();
//I want to find row with uniqueid, and remove it from the table
});
});
$(document).ready(function () {
$("#addbutton").click(function () {
var uniqueid = $("#textbox1").val();
var text = $("#textbox2").val();
$("<tr id=" + uniqueid + "><td>row content</td> </tr>").html(text).appendTo("#table1");
// instead of value add an id | tr does not have a value!
});
$("#removebutton").click(function () {
var uniqueid = $("#textbox1").val();
$('#' + uniqueid).remove(); // use id to delete row with the same id
});
});
FIDDLE
JSFIDDLE DEMO
$("#removebutton").click(function(){
var uniqueid = $("#textbox1").val();
$('#' + uniqueid).remove();
//I want to find row with uniqueid, and remove from table
});
I have this fiddle which is having user tab.In user tab ,there are three fields which accepts name,mobile and email.When a user fills all the three and hits add button then a row is inserted.Now i want to make the new added row editable.This means that I want to keep 2 bootstrap buttons edit and delete.So if delete is pressed then the entire row will be deleted and if edit is pressed then the entire will be editable where user can change the mobile number,name and email.Can any body please tell me how to do.
This js code adds new rows
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
This question is so specific to the OP scenario, so i will try to make the answer a bit more general.
I'm no expert here, but it seems you already capture the user's input and cloned it when they click Add to a new td. Therefore from what I understood is that you need to edit/delete the data from the new created td.
We have a table that contains several fields. We want to apply the following action on them
1- Add
2- Edit
3- Delete
Maybe this isn't the best practice, in short, my approach for this was to insert two spans for each data value:
One hidden that contains an input text field (inputSpan).
Another just contains plain text value (dataSpan).
Whenever you want to edit, dataSpan (just a data container) will disappear and inputSpan (text input field) appears instead enabling you to edit the text field. Once you edit and click Save the data in the text field will be cloned to replace the data in dataSpan. So basically dataSpan is just a reflection to inputSpan text field.
Here is an updated demo:
JSFiddle >> FullView Fiddle
I suggest for readability purposes, you break your code down into small function, it will make life easier, just sayin. So here general logic for your idea:
deleteRow = function (trID) {
// delete code goes here, remove the row
$(trID).remove();
}
manageEdit = function (tdNo) {
if ($("#edit-btn" + tdNo).html() === "Edit") {
$("#save-btn" + tdNo).show();//show save button
$("#edit-btn" + tdNo).html("Cancel");//change edit to cancle
editRow(tdNo);//call edit function
} else if ($("#edit-btn" + tdNo).html() === "Cancel") {
$("#save-btn" + tdNo).hide();//hide save button
$("#edit-btn" + tdNo).html("Edit");//change back edit button to edit
cancelEditRow(tdNo);
}
}
editRow = function (tdNo) {
$(".inputSpan" + tdNo).show();//show text input fields
$(".dataSpan" + tdNo).hide();//hide data display
}
cancelEditRow = function (tdNo) {
//looop thru 3 input fields by id last digit
for (var i = 0; i < 3; i++) {
//get input span that contain the text field
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
//get the data span that contain the display data
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
//text field inside inputSpan
var textField = inputSpan.find('input:text');
inputSpan.hide();//hide input span
textField.val(dataSpan.html());//take original data from display span and put it inside text field to cncle changes.
dataSpan.show();//show data span instead of edit field
}
}
saveRow = function (tdNo) {
//same as edit, but we reverse the data selection.
for (var i = 0; i < 3; i++) {
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
var textField = inputSpan.find('input:text');
inputSpan.hide();
dataSpan.html(textField.val());//take data from text field and put into dataSpan
dataSpan.show();
}
$("#edit-btn" + tdNo).html("Edit");//change text to edit
$("#save-btn" + tdNo).hide();//hide same button.
}
Here where I add the spans:
var tdCounter = 0;
$(".span4").each(function () {
var tid = val+"-"+tdCounter;
$tr.append("<td id='#mytd"+tid+"'>
<span id='inputSpan"+tid+"' class='inputSpan"+val+"' style='display:none'>
<input type='text' id='#input"+tid+"' value='"+ $(this).val() + "' /></span>
<span id='dataSpan"+tid+"' class='dataSpan"+val+"'>"+$(this).val()+"</td>");
tdCounter++;
});
Here I just append the buttons to call the functions, each button works for it's own row:
$tr.append("<td><botton id='edit-btn" + val + "' class='btn' onclick=manageEdit('" + val + "');>Edit</botton></td>");
$tr.append("<td><botton style='display:none' id='save-btn" + val + "' class='btn' onclick=saveRow('" + val + "');>Save</botton></td>");
$tr.append("<td><botton id='delete-btn" + val + "' class='btn' onclick=deleteRow('" + trID + "');>Delete</botton></td>");
Below is a sample function, it wont do everyhing you need, but it shows the jquery functions and one possibility how to do it. I only enabled editing name field, and deleting.
You would have to add other fields, + copy id data for the input.
js Fiddle
window.deleteRow = function (tar) {
$(tar).parent().remove();
}
window.editRow = function (tar) {
var row = $(tar).parent(),
cells, name;
cells = row.find("td");
name = $(cells.get(1)).text();
$(cells.get(1)).text('');
$(cells.get(1)).append('<input type="text" value="' + name + '">');
}
window.saveData = function() {
var data = {};
data.name = "some name";//get this from your input
data.email= "some email";//get this from your input
data.phone= "some phone";//get this from your input
$.get("http://yourphpsite.com", data, function(data, status) {
//data contains your server response
if (data.somepositiveservermessage) {
$("#user_notification_field").text("data saved");
$("#user_notification_field").show();
});
}