Under an ajax get method i need to generate table programatically.why actionlink not work with my table
ajax method
$(document).ready(function () {
//click event
$('.delete-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
//click event
$('.edit-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
$('.submitDetailForm').on('click', function () {
//get value from control
var ProductID = $('#ProductID').val();
var Qty = $('#Qty').val();
var Unit = $('#Unit').val();
var Amount = $('#Amount').val();
var ICMS = $('#ICMS').val();
var IPI = $('#IPI').val();
var ProductName = $('#ProductID option:selected').text();
var booksDiv = $("#booksDiv");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("AddToCard", "Sales")',
data: { ProductID: ProductID, ProductName: ProductName, Qty: Qty, Unit: Unit, Amount: Amount, ICMS: ICMS, IPI: IPI },
success: function (data) {
console.log(data);
var result = "";
booksDiv.html('');
$.each(data, function (SalesOrderID, OrderDetails) {
result += '<tr> <td>' + OrderDetails.Name + '</td>' +
'<td>' + OrderDetails.Qty + '</td>' +
'<td>' + OrderDetails.Unit + '</td>' +
'<td>' + OrderDetails.Amount + '</td>' +
'<td>' + OrderDetails.ICMS + '</td>' +
'<td>' + OrderDetails.IPI + '</td>' +
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>' +
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>' +
' </tr>';
});
booksDiv.html(result);
},
error: function (xhr, AJAXOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
});
});
Hyper link content
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>'
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>'
hyperlink display perfectly in browser but can not invoke click events
why my actionlink click event are not fired?
You need to use event delegation (using the .on() function) when adding dynamic content
$('#booksDiv').on('click', '.delete-logo', function() {
....
});
$('#booksDiv').on('click', '.edit-logo', function() {
....
});
where the element with id="booksDiv" is the closest ancestor that exists when the page is first generated.
Side note: Rather than manually generating your javascript object, you can simply use data: $('form').serialize(),
Related
here is my table snap enter image description here
I am creating this table from my model in razor view
it shows the structure of task and sub-tasks and their subtask ...
but the problem is it loads sub task and their subtask ... in the same level when someone clicks on the first column it loads its child under the parent
it's loads them and add a table row under the correspondence row
here is my jquery code I want to make it hierarchical like there should be a difference in parent and child level
function showHierarchy(taskId) {
if ($('.subtaskof_' + taskId).text() == '') {
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId, // request url
{
async: false,
success: function (data, status, xhr) {// success callback function
var subtasklist = JSON.parse(data)
console.log(subtasklist);
for (i = 0; i < subtasklist.length; i++) {
subtask = subtasklist[i];
var therowis = '<tr class=subtaskof_' + taskId + '>'
+ '<td id="subtaskrow_' + subtask['InstanceId'] + '" align="right">_</td>'
+ '<td>' + subtask['InstanceId'] + '</td>'
+ '<td>' + subtask["Title"] + '</td>'
+ '<td>' + subtask["Deliverables"] + '</td>'
+ '<td>' + subtask["StartDate"] + '</td>'
+ '<td>' + subtask["Priority"] + '</td>'
+ '<td>' + subtask["State"] + '</td>'
+ '<td>See Details_subt</td>'
+ '<td>Add Sub Task_subt</td>'
+ '</tr>'
// Find position to add new subtask row in the Task table
$("#my-grid tr").filter(function () {
if ($(this).text().indexOf(taskId) >= 0) {
$(this).after(therowis);
issubsubtaskexists = false;
console.log("chield checking for - " + subtask['InstanceId'])
$.ajax('/Tasks/sfsubtasks?taskId=' + subtask['InstanceId'], // request url
{
async: false,
success: function (data_, status_, xhr_) {
if (data_.length > 0) {
console.log("The data_ is - " + data_);
var subsubtasklist = JSON.parse(data_);
console.log("The subsubtasklist is - " + subsubtasklist)
console.log("lenght for - " + subtask['InstanceId'] + " , is - " + subsubtasklist);
if (subsubtasklist.length > 0) {
$('#subtaskrow_' + subtask['InstanceId']).html("<b><a style='font-size:25px; padding-left:17px;' id='lnk_" + subtask['InstanceId'] + "' href='#' onclick='showHierarchy(" + subtask['InstanceId'] + ")'> + </a></b>")
issubsubtaskexists = true;
}
}
}
});
console.log("The taskId is - "+taskId)
$('#lnk_' + taskId).html('<b>_</b>');
}
});
}
}
});
} else {
// Toggle/removing subtasks
$('.subtaskof_' + taskId).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId,
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist = JSON.parse(data)
console.log(subsubtasklist);
for (i = 0; i < subsubtasklist.length; i++) {
$('.subtaskof_' + subsubtasklist[i]['InstanceId']).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + subsubtasklist[i],
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist_ = JSON.parse(data)
console.log(subsubtasklist_);
for (j = 0; j < subsubtasklist_.length; j++) {
$('.subtaskof_' + subsubtasklist_[j]['InstanceId']).remove();
}
}
});
}
}
});
$('#lnk_' + taskId).html('<b>+</b>');
}
}
plz let me know what can be done of this table for showing data hierarchically
I have a javascript function that renders a table from an ajax call.
The row rendering bit is:
function buildTable(id) {
trHTML = null;
$.ajax({
type: "GET",
url: siteroot + "apiURL" + id,
data: {},
dataType: "json",
cache: false,
success: function (data) {
for (i = 0; i < data.length; i++) {
trHTML +=
'<tr>' +
'<td>' + data[i].value +
'<a class="pull-right" href="#" data-toggle="modal" data-target="#edit-modal" > ' +
'<span class="pull-right glyphicon glyphicon-pencil"></span>' +
'</a>' +
'</td>' +
'<td>' + data[i].text + '</td>' +
'<td>' + data[i].description + '</td>' +
'</tr>';
}
$('#resourceTable').append('<tbody>' + trHTML + '</tbody>');
},
error: function (msg) {
alert(msg.responseText);
}
});
}
And the modal is defined as:
<div th:replace="../../modals/modal"></div>
The issue I am facing is that the link is here on the rendered table, but when I click it, the modal does not come on.
What am I not seeing here?
Based on the database value status will be Y or N. If it Y means it will active.png will be displayed. it is working fine. when i click active.png image then anchor tag onclick="GetRecords1(' + item.ModuleID + '); Function the ID value is not passed to the event.
How to pass the active.png image click the ID value.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
} else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Pass:
<script>
$(document).ready(function () {
$('#example tbody').on('click', function GetRecords1(ModuleID) {
var id = ModuleID;
alert("Status Clicked:" + ModuleID);
});
});
</script>
<a id="123" onclick="someFunction(this.id)"></a>
JavaScript code:
someFunction(id) {
console.log(id)
}
Why are you using in-line JavaScript? You could easily use event delegate on to bind click events.
Here is your modified code:
Status = '<img src="/img/Active.png" height="22" width="42"/>'
Added a class user-status to a tag and assigned id to data-id attribute.
Now get id from click event:
$(document).on('click','.user-status', function(){
var getId = $(this).data('id');
var getStatus = $(this).data('status');
alert("Status Clicked:" + getId );
});
I'm trying to create a single-page app that pulls information from a JSON file, displays it on the screen, and perform a few actions.
Right now, I have all of the information being displayed on the screen properly: http://jsfiddle.net/rcsayf7t/3/
I need the "Remove" button to asynchronously remove the JSON object from the screen when it's clicked, but unfortunately have no idea how to go about accomplishing it.
HTML:
<table>
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Name</th>
<th scope="col">Message</th>
<th scope="col">Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody class="tweets-result"></tbody>
</table>
jQuery:
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td>Remove</td>' +
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
}
});
});
Live demo
Just add the following inside ajax success:
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
and the following code as remove attribute:
class="remove_row"
Full JS (read my comments):
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td class="remove_row">Remove</td>' + // ## Here add the class remove_row
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
//## Here assign the even on click for the remove button
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
}
});
});
I got two different roles, Admin and Associate.
An Admin should be able to delete a product while an Associate should not be able to delete a product.
I know how to configure this in the View by not showing the Delete Action Link for an logged in Associate user. However I have also implemented an onkeydown ajax search functionality that returns a list of jsonobjects. These json-objects are a list of product objects that matches the searchstring and then immediately builds up the markup in the view. This is done from a single javascript function.
The problem with this is that it now is hardcoded to generate delete action links, regardless of current logged in user role. So in a way, I need to modify my javascript function so that it doesn't generate delete actionlinks if the current logged in user is an associate user.
This is my function:
function searchProduct() {
var searchWord = $('#searchString').val();
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
$('.table').append('<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
'<a href=/Product/Details/' + item.Value + '>Details</a> |' +
'<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> |' +
'<a href=/Product/Delete/' + item.Value + '>Delete</a>' +
'</td>' +
'</tr>'
);
});
}
});
}
Triggered by this in the View:
<div class="form-group">
#Html.TextBox("searchString", "", new { onkeydown = "searchProduct();", onkeyup = "searchProduct();", onkeypress = "searchProduct();"})
<input type="submit" value="Search" class="btn btn-default" onclick="searchProduct()"/>
</div>
My Server code in the controller:
public JsonResult TextChangeEventSearch(string searchString)
{
var products = _productRepository.GetAll().ToList();
var result = products.Where(p => p.Name.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.Status).ThenBy(y => y.Name);
var jsonList = result.Select(p => new
{
Name = p.Name,
Status = p.Status,
Genre = p.Category.Name,
Value = p.Id.ToString(),
Warehouse = p.Stock
});
return Json(jsonList.ToList(), JsonRequestBehavior.AllowGet);
}
I think that I need access to the current logged in user role in the javascript function. Then I might be able to add one if statement in the function that prevents it from generating delete action links in the view if it is an associate user that uses this function.
Where do I go next with this? Any thoughts, explanations and help would be greatly appreciated.
May be you can render the role of the current user in one hidden field on the page and then use the value of that field to decide if delete button should be rendered.
#{
Layout = Model.Layout;
var isAssociate = Context.User.IsInRole("Associate"); //This is indicative and one of the approach of getting user role information at the client side. You can have your own mechanism to get the user's role information at the client side so that you can use it in your javascript.
}
<input type="hidden" value="#isAssociate"/>
and your javascript call will look like as following.
function searchProduct() {
var searchWord = $('#searchString').val();
var isAssociate = $('#isAssociate').val();
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
var htmlContent = '<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
'<a href=/Product/Details/' + item.Value + '>Details</a> |' +
'<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> ';
if(isAssociate == "false")
{
htmlContent += |' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
}
htmlContent += '</td>' + '</tr>'
$('.table').append(htmlContent);
});
}
}
});
NOTE : Here I am assuming that you have figured out a mechanism to identify the user role and you are able to store it so that it can be accessed in the view. If you don't have this then you need to figure out a way for that.
I am sure this will help you.
Thanks and regards,
Chetan Ranpariya
you're on the right track. the js needs to know! you could add a data attribute to the input, for example:
<input data-is-admin="false" ....>
and then check this attribute in the js. and you'll propably want to authorize any delete on your server anyway.
Once you have the data in JavaScript you can use an online if statement to only show delete button for admin:
'...' + ( userRole == 'Admin' ? '[Delete button HTML]' || '') + '...'
It's been a while, but I got back to this issue many weeks later, and I solved it like this:
At the top of the view:
#{
ViewBag.Title = "Index";
var isAdmin = Context.User.IsInRole("Admin");
}
Javascript function:
function searchProduct() {
var searchWord = $('#searchString').val();
var isAdmin = "#isAdmin";
$.ajax({
url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
type: 'GET',
datatype: 'json',
contenttype: 'application/json',
success: function (data) {
$('.table tr:gt(0)').detach();
$.each(data, function (i, item) {
var htmlContent = '<tr>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Status + '</td>' +
'<td>' + item.Genre + '</td>' +
'<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> | ' +
'<a href=/Product/Details/' + item.Value + '>Details</a> | ' +
'<a href=/Product/Discount/' + item.Value + '>Discount</a> ';
if (isAdmin.toString() === "True")
{
htmlContent += '| ' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
}
htmlContent += '</td>' + '</tr>'
$('.table').append(htmlContent);
});
}
});
}