how to get a value of parent id with jquery - javascript

HTML
<tr>
<td>No.</td>
<td id="2" class="editable">data1</td>
<td id="2" class="editable">data2</td>
<td>Usage Left</td>
</tr>
<!-- Multiple rows with different ids -->
javascript
<script type="text/javascript">
$(function () {
$('.editable').editable({ onSubmit: Update });
function Update() {
var id = $(this).parent('td').attr('id');
var title = $(this).text();
$.ajax({
type: 'post',
url: 'update.php',
data: 'title=' + title + '&id=' + id,
success: function (response) {
$('#response').fadeIn('1000').empty().append(response);
}
});
}
});
</script>
I want to get the value of the ids of class editable, this is an inline edit plugin i am using I am able to collect the data1 and data2 values but for id, I am getting undefined.
What is wrong with my code.
Thank You.

Shouldn't it be just $(this).attr('id')?
You are attaching the event to td. So this inside the event handler refers to the td itself.

Related

How to remove clicked row while sending parametr to a function? Knockout

I have some complication with service removing. I have function that removes service on the server but I have to reload page to update table. I found way how to remove row by click-binding but there is the issue beacuse I can only remove row or get ID for delete service from server NOT both. :/
This is example of code that removes service on the server but doesn't remove table row.
HTML:
<table id="serviceView" class="fixed_header" border: 1>
<thead>
<tr>
<th>Name</th>
<th>Adress</th>
<th>Notification</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
<td data-bind="text: serviceId"></td>
<td ><button data-bind="click: $parent.DeleteService.bind(this, serviceId)">Remove</button></td>
</tr>
</tbody>
</table>
JS:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
self.DeleteService = function (serviceId) {
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
This is example of code that removes table row
When I use click-binding like this:
<button data-bind="click: $parent.DeleteService">Remove</button>
And change delete function to this:
self.DeleteService = function (serviceId) {
self.services.remove(serviceId)
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
// here I want to remove row but i doesnt goes here without service ID.
})
};
It removes row but instead serviceId I got [object, object] in the URL.
Can you help me with it ? I got idea to use jquery to just update the table but it's seems unnecessarily complicated for me when I can use knockout.
I know the solution is not that hard but I'am just unable to solve it..... -_-
I'am sorry for taking time with this bullshit but this is my first real project and I'am so desperate at this point beacuse I have lot of things to do and I'am stucked on this.
In your Js code, you can try this:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
var serviceIdRemoved;
self.DeleteService = function (serviceId) {
serviceIdRemoved = serviceId; // now you can do whatever you need more with this value
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
With this way of work you can user the content of the variable and donĀ“t loose it. Also if you get [Object, Object], you can:
console.log(serviceId) // to see the content in the console.
JSON.stringify(data) //to see the content in html
This source could help you to understand it better.
The [object, object] you are seeing is actually the data and event objects which are secretly added to the JS function parameters by Knockout. If you want to add your own parameter to the click binding then you should do it like this:
<button data-bind="click: function(data, event) { $parent.DeleteService(serviceId, data, event) }">Remove</button>
You can then define your JS function as follows:
self.DeleteService = function (serviceId, data, event) {
[code here...]
}
You can read up on the exact details of it in the excellent Knockout documentation here:
http://knockoutjs.com/documentation/click-binding.html
It's about half-way down under the heading that reads Note 2: Accessing the event object, or passing more parameters

How To Find Id From Anchor Tag Using Jquery

Here i am trying to find the taskid present in anchor tag using Jquery on click of that anchor tag having class=POtskComment.But as i click the anchor tag taskid id is undefined.
Any help will be heartly thankful.Thank You
Below is my Html
#foreach (var item1 in Model)
{
<tbody>
<tr>
<td>
<a class="POtskComment" taskid="#item1.TaskId" tskassinid="#item1.TskAssId" tskname="#item1.TaskName">
#Html.DisplayFor(modelItem => item1.TaskName)
</a>
</td>
</tr>
</tbody>
}
Below Is Jquery
<script>
$(document).ready(function (event) {
$(".POtskComment").click(function (event) {
var paramTaskId3 = $(this).closest("tr").find("td").attr("tskid");
var parameter = { taskId: paramTaskId };
$.ajax({
url: "/TaskAssignedDailyLogs/_POIndex",
type: "get",
dataType: "html",
data: parameter,
success: function (data)
{
$("#reportResult").html(data);
}
});
});
});
</script>
Try this
var paramTaskId3 = $(this).attr("taskid");
the attribute is also misspelled
typo: it should be 'taskid' and not 'tskid'
your attr is on the anchor tag, and not td tag,
hence use $(this).attr('taskid');

Get id from td of a table

<script type="text/javascript">
function LoadData(){
var url = serverURL+"/List.php";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data){
$.each(data.data, function (key, value) {
var doc_id=value['id'];
var doc_name=value['name'];
var doc_speci = value['specialize'];
$("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");
});
},
error: function(data){
toastr.error("Opps! Something went wrong");
$(".se-pre-con").fadeOut("slow");
},
});
}
</script>
The above appends a tr to my html table below.
The HTML TABLE is as follows:
<table id="myTable" class='table table-bordered table-hover table-striped'>
<tr>
<th>Name</th>
<th>Specialization</th>
<th>Action</th>
</tr>
</table>
Now i want to retrieve the id from the data attribute from td class retrieve so that i can send the id and redirect it to other page for editing.
// Clicks the edit field
$("td.retrieve").on("click", function(e) {
var id = $(e.currentTarget).attr("data-did");
// do with the ID what you want
alert(id);
});
I'm aware that jQuery has a "data(...)" function but I've run into issues with that sometimes in the past. "attr(...)" will do something similar but relies specifically on the attribute instead of stored objects.
First, to add your data attribute you should make sure you add quotes around the value:
data-did='"+doc_id+"'...
So the rendered cell must look something like this:
<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>
(where n is some value)
Then you can easily retrieve this value with jQuery:
$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example
To get all of the rows:
var ids = [];
$('.retrieve').each(function() {
ids.push($(this).data('did'));
});
Example:
If you have a button for example:
$('#myTable').on('click', '.retrieve input[type="button"]', function() {
var id = $(this).parent().data('did');
alert(id);
});
JSFiddle: https://jsfiddle.net/y2an0fu7/1/

How to load a partial view by clicking a row in the table

I have two partial views, one is _UserList and the other one is _UserDetail and both of them are shown in index.
[index.cshtml]
#Styles.Render("~/Content/PagedList.css")
<h2>UserManagement</h2>
<hr />
<div id="UserList">
#Html.Partial("_UserList")
</div>
<hr />
<div id="UserDetail"></div>
<hr />
I already have a link named Details that is implemented with Ajax.ActionLink to show the detail in every rows.
And the link's source code is:
[_UserList.cshtml]
#Ajax.ActionLink("Details", "UserDetail", new { userId = item.ID }, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UserDetail" })
After click "Details", _UserDetail will be shown under _UserList.
Now, I want to implement a clickable row that can load _UserDetail with a parameter: item.ID when I click on a row of the table in _UserList.
I have tried a lot of ways but I still cannot implement it successfully.
Could anyone give me a hand?
Finally, I found a way to implement this feature with jQuery.
And the source code is as below:
<table class="table table-hover>
#foreach (var item in Model.TlmAbstractPagedList)
{
<tr data-id="#item.TlmId" class="clickableRow">
<td>
#Html.DisplayFor(u => item.DateStart) ~ #Html.DisplayFor(u => item.DateEnd)
</td>
<td>
#Html.DisplayFor(u => item.Name)
</td>
<td>
#foreach (var product in item.ProductInformation)
{
<ul>product.ProductNameWithId</ul>
}
</td>
</tr>
}
</table>
<script>
$('.clickableRow').click(function () {
var targetRow = $(this).data('id');
$.ajax({
url: 'TlmManagement/TlmReport',
data: { tlmId: targetRow },
method: "GET",
success: function (data) {
$("#TlmDetail").empty();
$("#TlmReport").empty();
$("#TlmReport").html(data);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
})
</script>
I assign data-id to every row and the class click function will check this data-id to find out which row is being clicked and then make display of the data.
Hope this source code will help someone.

How to fetch data from file using ajax on clicking table rows

I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});

Categories