Click event on Button INSIDE table - javascript

How to open Modal Dialog from when I click on Button inside table?
function GetAllCountries() {
$('#update_panel').html('Loading Date....');
$('#update_panel').html("<img src='/Pic/ajax-loader.gif'/>")
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table id="tableItems"> </table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
});
$('#update_panel').html($data);
}
else {
var $noData = $('<div/>').html('No Data Found!');
$('#update_panel').html($noData);
}
},
error: function () {
alert('Error! Please try again.');
}
});
}
I tried the following code but didn't work
$("#mybtn").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,
});
$("#CreateForm").dialog('open');
})
I think I need something like to reach the button INSIDE the table and add click event of it
$("#Table: Tbody,th,tr").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,

When you create the button you also have to set the click event. Any event created before the initialization of an element won't be attached to that specific element. So change your code from this:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
To this:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$button = $('<button />', {class: 'whatever', id: 'myButton' /* AND SO ON */};
$($button).click(function() {
// CODE TO OPEN THE MODAL
});
$row.append($button);
$data.append($row);
* EDIT *
beanId recover
I hope the code is clear. Anyway Using HTML5 data attribute, you can easily recover the ID of the bean you have to edit. You can also use the action anchor to open a modal, and set to that modal specific values.
$(document).ready(function() {
$('.actionButton').click(function() {
// Recover data-bean-id tag value
var beanId = $(this).data('beanId');
// Do whatever you want
alert('Bean value:' + beanId)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- ** The 'actionButton' anchor can be also used to open a modal -->
<table id="myTable">
<thead>
<tr>
<td>#</td>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>ACTIONS</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="1">ACTION</a></td>
</tr>
<tr>
<td>2</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="2">ACTION</a></td>
</tr>
<tr>
<td>3</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="3">ACTION</a></td>
</tr>
</tbody>
</table>

Related

Get attribute value from datatables row for every record

I am working with datatables and I want to edit and delete data table records
When I do console.log(row) following output I get:
["user1", "Edit"]
(index):274 (2) ["user2", "Edit"]
(index):274 (2) ["user3", "Edit"]
(index):274 (2) ["user4", "Edit"]
(index):274 (2) ["user5", "Edit"]
What I want is to get data-id from render: function (data, type, row) which I have used in datatable script and when click on edit button I want to get specific id in alert but I am unable to extract data-id.
My jQuery code:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#catgeory_list').DataTable({
processing: true,
language: {
emptyTable: 'no result found.'
},
columnDefs: [{
visible: true,
targets: 0,
render: function (data, type, full, meta) {
return data;
}
}, {
visible: true,
targets: 1,
render: function (data, type, row) {
console.log(row);
return '<button id="editBtn" class="btn btn-wrang btn-flat edit" name="editBtn" type="button">Edit</button>' + ' <button id="deleteBtn" class="btn btn-danger btn-flat delete" name="deleteBtn" type="button" >Delete</button>';
}
}
],
});
In order to get any source object/array property/item for the row being clicked, you don't need anything more than simple row().data() API method invoked against DataTable row (selected by the closest to the clicked button <tr> node):
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
Here, dataTable is a variable, you assign your DataTable to.
Full-blown DEMO you might find below.
Also, considering your ultimate goal, you might find of use my answer over here, which provides complete working demo of editable DataTable. So, if you find that helpful, upvotes are appreciated ;)
//src data
const srcData = [
{id: 1, item: 'apple'},
{id: 2, item: 'banana'},
{id: 3, item: 'tomato'}
];
//datatables init
const dataTable = $('table').DataTable({
dom: 't',
data: srcData,
columns: [{data: 'item', title: 'Item Name', render: data => data+'<button>Show Id</button>'}]
});
//click handler
$('table').on('click', 'tbody td button', function(){
const rowData = dataTable.row($(this).closest('tr')).data();
alert(`Row ID is ${rowData.id}`);
});
td button {float: right}
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table></table></body></html>
You can wrap data or row parameter from callback function with jQuery $() to get any element/node attributes or DOM manipuation. Refer also toJQuery() for dealing with Datatables API instances.
Render
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
createdRow
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
Click Event
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
Working Live Demo:
$(document).ready( function () {
var table = $('#example').DataTable({
columnDefs: [
{
targets: 1,
render: function(data, type, row, meta){
var data_id = $(data).data('id');
console.log('Columns.Render:',data_id);
return data + " : data-id(" + data_id+")";
}
},
],
createdRow: function (row, data, index) {
var data_id = $('td a.edit_row', row).data('id');
console.log('CreatedRow:',data_id);
}
});
$("a.edit_row").click(function(){
var data_id = $(this).data('id');
alert(data_id);
});
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css"
rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Edit</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Edit</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$4,800</td>
</tr>
</tbody>
</table>

Dynamically add Select2 to Row

why when i try to add select2 to new row the new select2 failed to initialize (it shown as select html tag).
Here's my code to create the table :
<table id="tbldet" class="table table-bordered table-striped table-hover" style="width:100%;margin:0 auto;">
<thead>
<tr>
<th><p>Nama Barang</p></th>
<th><p>Harga</p></th>
<th><p>Qty</p></th>
<th><p>Total</p></th>
<th style="width:50px"><p>Aksi</p></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="select2" name="det_brg" style="width:100%;">
</select>
</td>
<td>10000</td>
<td>4</td>
<td>930000</td>
<td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>
</tr>
</tbody>
</table>
javascript function to initializeSelect :
function initializeSelect2(selectElementObj) {
selectElementObj.select2({
width: "80%",
tags: true,
language:"id",
ajax: {
url: "controller/barang_list.php",
dataType: "json",
type:"GET",
delay: 250,
data: function (params) {
return {
search: params.term
}
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id:item.id,
text:item.text
}
})
};
},
cache: false
},
minimumInputLength: 3,
dropdownParent:$("#form-data")
});
};
$(".select2").each(function() {
initializeSelect2($(this));
});
here's the code to add new row :
//create new row
$("#add_row").click(function(e) {
//new row
$("#tbldet").append(
'<tr>\
<td>\
<select class="select2" name="det_brg" style="width:100%;">\
</select>\
</td>\
<td>10000</td>\
<td>4</td>\
<td>930000</td>\
<td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>\
</tr>'
);
var newSelect=$(this).closest("tr").find(".select2");
initializeSelect2(newSelect);
})
i suspect there's problem with finding new 'select2' component on new row, but when i use alert(newSelect) it didn't show NULL / Undefined
Your suspicion is correct, your code will never find the new .select2 element. The reason has to do with the way .closest() works. You can investigate that here:
https://api.jquery.com/closest/
But in the mean time:
Change
var newSelect=$(this).closest("tr").find(".select2");
TO
var newSelect=$("#tbldet").find(".select2").last();

Display confirmation message next to a single table row

Trying to show "Product Added!" message to the right of the row where the user selected 'Add'. The way I have it right now is:
var addToCart = function (idFromButton) {
$.ajax({
type: "POST",
data: { prodID: idFromButton },
url: '#Url.Action("Add", "ShoppingCart")',
success: function (data)
{
$('#BadgeIcon').html(data).fadeOut(1).fadeIn('fast');
$('.fakeLink-' + idFromButton).text("Product Added!").css("color", "green").fadeIn(600).fadeOut("slow");
}
});
}
which changes the 'Add' button green and fades it away.
I have also tried creating a new row element to the right of the 'Add' column and adding the message there. It works, but moves the 'Add' button to the left during the fading animation, not to mention that it permanently removes the border of that last column upon click until page is refreshed.
Here is my table:
<table class="table" id="table">
<tr>
<th>
Product Name
</th>
<th>
Price
</th>
<th>
Image
</th>
<th>
Add to Cart
</th>
</tr>
#if (Model.Results.Any())
{
foreach (var item in Model.Results)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#item.Price.ToString("$0.00")
</td>
<td>
#if (item.ImageFile != null)
{
<img src="#Url.Content(item.ImageFile)" />
}
</td>
<td>
<input id="fakeLink" class="fakeLink-#item.ProductID" type="submit" value="Add" onclick="addToCart(#item.ProductID)" />
</td>
</tr>
}
}
else
{
<tr>
<td colspan="4">No product found.</td>
</tr>
}
</table>
Any help would be greatly appreciated.
Your code looks fine except you need to update the button's value, not text. You may use the val() method.
$('.fakeLink-' + idFromButton).val("Product Added!")
.css("color", "green").fadeIn(600).fadeOut("slow");
Also, i see you have duplicate id values for your button's inside the loop. Your id's should be unique. Actually you do not really need an Id for this case. You can simplify your code with unobutrusive javascript like this
<td>
<input class="addBtn" data-product="#item.ProductID" type="submit" value="Add" />
</td>
and listen to the click event of this type of button (button with addBtn css class) and you can use $(this) as the reference of clicked button.
$(function() {
$(".addBtn").click(function(e) {
e.preventDefault();
var _this = $(this);
$.ajax({
type: "POST",
data: { prodID: _this.data("product") },
url: '#Url.Action("Add", "ShoppingCart")',
success: function (data) {
_this.val("Product Added!").css("color", "green").fadeIn(600)
.fadeOut("slow");
}
});
});
});
EDIT : If you want to keep the Add button intact, but want to show a message next to that, you can do this.
success: function (data) {
var msg = $("<span />").html("Product added").css("display","none");
msg.appendTo(_this.parent()).fadeIn(500).fadeOut("slow");
}
You may apply additional css styles to the message span as needed.

How to update an existing row with HTML on an existing JQuery Datatables?

I have an existing jQuery dataTables object in my html page.
I need to update a few <a href> elements in all <td>s on the first <tr> of the datatables by clicking on a refresh button which triggers an Ajax call to retrieve the new data in JSON.
The <a href> elements are dynamically constructed with the hyper links retrieved by Ajax, so I need to have the html for each <a href> element.
<tr id="LoJXi76DH3" role="row" class="odd">
<td><a data-transition="pop" data-mini="true" data-position-to="window" data-rel="popup" href="#deleteThisRunModel" onclick="copyRunModelObjId("LoJXi76DH3");" title="Delete this job"><img width="16" height="16" src="css/img/Remove24.png"></a></td>
<td><span>LoJXi76DH3</span></td>
<td><span>500</span></td>
<td><span>Completed</span></td>
<td><span>Firstname Lastname</span></td>
<td><span>9/12/2015, 1:07:39 PM</span></td>
<td><span>9/12/2015, 1:18:47 PM</span></td>
<td><span>Successful</span><span> </span><a title="Details" class="my-tooltip-btn ui-btn ui-alt-icon ui-nodisc-icon ui-btn-inline ui-icon-info ui-btn-icon-notext" data-transition="pop" data-rel="popup" href="#popupRMDetails_LoJXi76DH3">Details</a></td>
<td><a target="_blank" href="View.jsp?res=500&url=myImage.png">View</a><span> </span>Download</td>
</tr>
Just wondering which function/api should I use to get this done?
If you want to replace an entire <tr>..</tr> with a brand new or modified <tr>, you can do the following.
First locate the row you want to replace in jQuery, either with some id selector or through DOM traversal from an event like this:
var $row = $(this).closest("tr")
Let's say you have an brand new HTML row that you'd like to replace it with. This could come from an AJAX call, somewhere on the page, or a modified version of the existing row, or just straight HTML:
var newRow = $("<tr> <td>1</td> <td>Bob</td> <td><i>23</i></td> <tr>
If this was a plain HTML table, you could just do .replaceWith() like this:
$row.replaceWith($(newRow))
Buutttt, then DataTables doesn't know about it, so the next time you call $dt.draw(), it'll change back. Instead, you have to pass the new info into the DataTable by locating the row in DataTables and then handing it the new info.
row().data() - data represents an array of string values that are the innerHTML of each td
So we need to convert the above row to something like this:
["1","Bob","<i>23</i>"]
Here's a function that converts a row to a data table array:
function TrToData(row) {
return $(row).find('td').map(function(i,el) {
return el.innerHTML;
}).get();
}
So the whole thing will look something like this:
$('.replace').click(function () {
var $row = $(this).closest("tr")
var newRow = $("#newRow").find("tr")[0].outerHTML
var newRowDataArray = TrToData(newRow)
$dt.row($row).data(newRowDataArray).draw();
});
Demo in jsFiddle
Demon in Stack Snippets
$(function() {
// initialize table
var $dt = $('#example').DataTable({
paging: false,
bFilter: false,
bInfo: false
});
// add row
$('#addRow').click(function () {
//$dt.row.add( [1,2,3] ).draw();
var newRow = $("#newRow").find("tr")[0].outerHTML
$dt.row.add($(newRow)).draw();
});
// replace row
$('.replace').click(function () {
var $row = $(this).closest("tr")
var newRow = $("#newRow").find("tr")[0].outerHTML
var newRowDataArray = TrToData(newRow)
//$row.replaceWith($(newRow))
//data represents an array of string values that are the innerHTML of each td
$dt.row($row).data(newRowDataArray).draw();
});
function TrToData(row) {
return $(row).find('td').map(function(i,el) {
return el.innerHTML;
}).get();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/jquery.dataTables.js"></script>
<table id="example" class="display" cellspacing="0" >
<thead>
<tr>
<th>Hidden</th>
<th>Name</th>
<th>Age</th>
<th>Replace</th>
</tr>
</thead>
<tbody>
<tr>
<td>Line 1 <input type="hidden" value="1"/> </td>
<td>Bob <input type="hidden" value="Bob"/> </td>
<td><input type="text" value="18"/> </td>
<td><input type="button" value="Replace" class="replace"/> </td>
</tr>
</tbody>
</table>
<br/>
<button id="addRow">Add New Row</button>
<table id="newRow" style="display:none">
<tbody>
<tr >
<td>Line 2 <input type="hidden" value="2"/> </td>
<td>Ann <input type="hidden" value="Ann"/> </td>
<td><input type="text" value="21"/> </td>
<td><input type="button" value="Replace" class="replace"/> </td>
</tr>
</tbody>
</table>
you can use jQuery for updating a specified row. for this you need to define unique id for each row. then by the following id, you can get the object of the table element and update it by ajax call. let me explain by code. here also shown how to manipulate dynamic links.
function updateJobStatus() {
$("#data-table tr.running").each(function() {
var obj = $(this);
var id = $(this).find('td:eq(0)').text();
//var id1 = $(this).attr('id');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'ajaxGetPrintJob.html',
data: 'id=' + id,
success: function(responseData,textStatus) {
if (textStatus == 'success' && responseData.length > 0) {
var id = responseData[0].id;
var tagId = responseData[0].voterListTagId;
var createdBy = responseData[0].createdByName;
var locationType = responseData[0].locationType;
var totalJobCount = responseData[0].totalJobCount;
var successCount = responseData[0].successCount;
var failedCount = responseData[0].failedCount;
var status = responseData[0].status;
$(obj).find('td:eq(0)').html(id);
$(obj).find('td:eq(1)').html('<input name="app_id" id="row'+id+ '" type="checkbox" value="'+id+'" class="case"/>');
$(obj).find('td:eq(2)').html(''+responseData[0].name+'');
$(obj).find('td:eq(3)').html(createdBy);
$(obj).find('td:eq(4)').html(totalJobCount);
$(obj).find('td:eq(5)').html(successCount);
$(obj).find('td:eq(6)').html(failedCount);
$(obj).find('td:eq(7)').html(status);
}
}, error: function(responseData) {
unblockView();
}
});
});
setTimeout(updateJobStatus, 20000);
}
here updateJobStatus() function will fire every 20 sec by ajax calling getting data and also manipulate.
here data-table refers the table id.
<table summary="search result" id="data-table" class="search-result" cellspacing="0" style="">
and the table row should be like,
<tr class="<c:if test="${loop.count % 2 !=0}"> odd-row </c:if> <c:if test="${result.status eq 'INITIALIZING'}"> running </c:if>" >

Making table row clickable in jsp

I am having table rows and I want to make the whole row clickable.So to do it I right the following ajax code :
$(document).ready(function() {
$('#myrow').click(function ()
{
//alert("hi");
$.ajax({
type: "post",
url: "shownotification.jsp",
data: {
notifyidd: $('#notifyidd').val(),
notifyuser: $('#notifyuser').val()
},
success: function(msg){
//if(msg == "success")
alert('Data updated.');
window.location.reload();
}
});
});
});
But the problem is that it just make my first row clickable, and all other are still not.
What can be the reason? Please help.
Seem like currently you're having duplicated id for your tr, try to apply class instead:
<tr class="myrow" ......
then you can use . to target elements by class:
$(document).ready(function() {
$('.myrow').click(function () {
// Your code here
});
});
bind you code with on and also done with previous code
HTML
<table>
<tbody>
<tr class="myrow">.......
</tr>
</tbody>
</table>
jQuery
you can try two method
$(document).ready(function() {
$('.myrow').click(function ()
{
//your stuff
});
/***or can try this below method**/
$('table').on('click', 'tr', function() {
//your stuff
});
});
Try this
$(document).on('click', '#table-id tr', function() {
alert('Hello');
});
In Your Code you are giving click event on id
i.e. $('#myrow').click(function ()
So it is no working because id of div must be unique. change your rows id with class name then it will work fine
$('.myrow').click(function ()
Refer below link for reference
Demo Link
Table HTML is
<table style="width:300px">
<tr class="tableRow">
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr class="tableRow">
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr class="tableRow">
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
Script for click event
$(".tableRow").click(function(e){
alert("Table Tr Clicked");
});

Categories