I have wrote a function in javascript which takes title attributes of <tr> calls ajax then after some operation it retreive some title attributes from them. depending on that title attribute i want to remove those <tr> rows
function currentTicketStatus() {
var ids = '';
$('tbody tr[title]').each(function() {
ids += ((ids == '') ? '' : ',') + $(this).attr('title');
});
$.ajax({
url: 'ajaxExecute.aspx?Fn=CTS',
type: 'POST',
context: document.body,
cache: false,
data: 'Tickets=' + ids,
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
sTickets.each(function() {
$(this).parent().parent().remove();
});
}
}
}
});
}
Example : at the time of ajax call ids="100,101,102,103,104" after ajax call sTickets="101|102" . Now remove those rows with attributes of sTickets
HTML (Not Exactly )
<tbody>
<tr title="100"> some data part </tr>
<tr title="101"> some data part </tr>
<tr title="102"> some data part </tr>
<tr title="103"> some data part </tr>
</tbody>
the this in the each is a "title" (a string), you need the DOM element (the <tr>) instead
sTickets.each(function() {
$('tbody tr[title="'+ this +'"]').remove();
});
demo
try this code in your success function :
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
$.each(function(i,v){ $('tr[title=' + v + ']') }).remove();
}
}
Explanation:
1- SELECT DOM element by attribute :
$('[ATTRIBUTE=VALUE]') // $('[title="myTitle"]')
you can find more in this link http://api.jquery.com/attribute-equals-selector/
2 - $.each Iteration
which can be used to seamlessly iterate over both objects and arrays.
more : http://api.jquery.com/jquery.each/
Related
I loop through some data dynamically via Ajax and than display them in table. As you see I have multiple row or <tr> , HeaderLine and Customerinfo. which I'm interesting in is CustomerInfo and the thing I'm trying do is when button is clicked, check which input fields is Empty or has no value than give an alert and for finding input fields or elements I used jQuery find() and closest() Method, but for some reason it can't find any elements.
Can anyone please help me to solve the issue?
JavaScript for checking Empty input fields before sending to server:
<script>
function AnmodomRMA(e) {
var tr = $(e).closest("table").find(".CustomerInfo");
var email = tr.find('input.Email').val();
var telefon = tr.find('input.Telefonnummer').val();
if (email === "") {
alert("Input is Empty:" + email);
return false;
}
if (telefon === "") {
alert("Input is Empty:" + telefon);
return false;
}
var formdata = $("select, textarea,input").serializeArray();
$.ajax({
"url": '#Url.Action("AutoRMAAnmoding", "User")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
console.log(data);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
JavaScript for Load Data (dynamically into table):
<div class="card-body">
<table class="table">
<tbody id="ResultProduct"></tbody>
</table>
<div id="AppendBtnRMA">
</div>
</div>
<script>
$.ajax({
type: "GET",
url: "/User/serializeItemLineByID" + 1,
dataType: 'json',
success: function (result) {
$.each(result.findclosedorders, function (ii, e) {
var guid = uuidv4();
rows += '<tr class="HeaderLine">';
rows += '<td>some data</td>';
rows += '</tr>';
rows += '<tr class="CustomerInfo">'
rows += '<input type="hidden" name="model.InsertRMALists.Index" value="' + guid + '" />';
rows += '<td><label>Telefonnummer</label><input name="model.InsertRMALists[' + guid + '].Telefonnummer" id="Telefonnummer" type="tel"></td>';
rows += '<td><label>E-mail</label><input name="model.InsertRMALists[' + guid + '].Email" id="Email" type="text"></td>';
rows += '</tr>';
});
var btnAppend = "";
btnAppend += '<button onclick="AnmodomRMA(this);">Create RMA</button>';
$("#AppendBtnRMA").append(btnAppend);
$("#ResultProduct").append(rows);
},
})
</script>
Thanks for all help :)
Here is how did i solve the problems:
- Add a class to input fields.
- beacuse button it was out side the table, i have to select closest element around table and than find <tr> like:
var tr = $(e).closest(".card-body").find("tr.section");
and than loop through that element i want to check if it is Empty:
$(tr).each(function (i, el) {
var t = $(el).find('input.Telefonnummer').val();
if (t ==="") {
alert("empty");
}
});
In the function AnmodomRMA(e) e refers to the event itself and not the clicked button, try to use e.target:
var tr = $(e.target).closest("tr");
I have to grab "data" items and loop and inject to specific table like bellow. How is that possible from javascript/jquery? I have attached picture of my Json response of ajax call check to get idea about Json i need to be processed. Any question welcome. Thanks in advance....
Table:
<table>
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
<tr need to loop this tr as per json objects>
<td><img src="link defined from json value"></td>
<td>title from json value</td>
</tr>
</table>
Jquery Ajax call:
$.post("/CategoryResearch/Search", { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location })
.done(function (data) {
if (data != null) {
$("#normalState").fadeOut();
//Loop and inject html table data to specific table
console.log(data);
}
});
Json Picture from console.log(data) -
Table:
(dont forget to add tableId as id and remove de tr tag of sample data)
<table id="tableId">
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
</table>
Jquery Ajax call:
(on edit i'm placing the entire loop directly in ajax call for simplify to you)
$.post("/CategoryResearch/Search", { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location })
.done(function (data) {
if (data != null) {
$("#normalState").fadeOut();
//Loop and inject html table data to specific table
if ($("#tableId tbody").length === 0) {
$("#tableId").append("<tbody></tbody>");
}
var jsonDataObject = JSON.parse(data);
$.each(jsonDataObject, function(i, item){
$("#tableId tbody").append(
"<tr>" +
"<td><img src=\"" + item.EbayImageUrl + "\"></td>"
"<td>" + item.EbayTitle + "</td>" +
"</tr>"
);
});
console.log(data);
}
});
You can loop through the array that you get as a response with a for...
$.ajax({
type: 'POST',
url: '/CategoryResearch/Search',
data: { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location },
dataType: 'json',
success: function(data) {
if (data != null) {
$("#normalState").fadeOut();
var rows = [];
for (var i=0, l=data.length; i<l; i++)
rows.push('<tr><td>'+data[i].EbayImageUrl+'</td><td>'+data[i].EbayTitle+'</td></tr>');
$('table tbody').html(rows.join(''));
}
}
});
have you tried using append?
<table id="appendedTable">
<tr>
<th>
header 1
</th>
</tr>
</table>
<script>
$(document).ready(function(){
$('#appendedTable').append('<tr><td>concatenate here your json value</td></tr>');
});
</script>
Parse the response
(I think I'm wrong about this part. I haven't used jQuery in years. I think it parses it for you, but, just in case...)
The response from the server is a string. Parse it with JSON.parse.
let myData = JSON.parse(data);
Based on the supplied screenshot, it looks like you get an array of objects.
Iterate the array
Loop over each element of the array with Array.forEach.
Add Rows to your table
Get a reference to your table with document.getElementsByTagName or document.getElementById, et al.
Add rows and cells with HTMLTableElement.insertRow() and HTMLTableRowElement.insertCell().
Example
const myData = [{
EbayImageUrl: 'http://via.placeholder.com/100x50/ff0000/ffffff',
EbayTitle: 'example title'
}, {
EbayImageUrl: 'http://via.placeholder.com/100x50/00ff00/ffffff',
EbayTitle: 'example title'
}, {
EbayImageUrl: 'http://via.placeholder.com/100x50/0000ff/ffffff',
EbayTitle: 'example title'
}];
const table = document.getElementsByTagName('table')[0];
myData.forEach(item => {
let row = table.insertRow();
row.insertCell().innerHTML = `<img src="${item.EbayImageUrl}">`;
row.insertCell().innerHTML = item.EbayTitle;
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<table>
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
</table>
I have a simple view that show a table of data, I want to sort one of its columns when the header is clicked by AJAX, I'm new to AJAX and JS, so this was my try in the view:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('desc')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
#section scripts{
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData/' + srt,
dataTtype: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
}
but when I click the header the sort parameter goes null in the action,
public JsonResult BooksData(string sort)
{
var books = new List<Book>();
if (sort == "asc") books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
else books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
return Json(books, JsonRequestBehavior.AllowGet);
}
Yes I'm doing it wrong, but I revised it many times, I can't see logical error except that passing parameters in JavaScript is different than C#
Here is the simpliest way.You need to concatenate sort value to url, using query string.
Now, when you click header the sort parameter must goes with your value in the action.
Please try this:
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataType: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
Another way is to use this:
url: '#Url.Action("BooksData","Book")?sort=' + srt
The #Url.Action returns just a string.
In Razor every content using a # block is automatically HTML encoded by Razor.
I have a very frustrating issue. I have two kind of paragraphs in a div , a built in one like you see below
<div >
<table id="box">
<thead>
<tr>
<td><p class="linkin" data-value="test22">test</p></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
And fetched ones like this:
$('.menu').on('click', function(){
$('#box').toggle('slide').show();
$.ajax({
url:'fetchsubmenu.php',
data : {nume : $(this).attr('data-value')},
dataType : 'json',
success:function(data){
console.log(data);// process your response
showObjects(data);
}
});
});
function showObjects(obiecte){
$('#box tbody').html('');
for(var i=0; i<obiecte.length; i++){ //Functia care arata obiectele
var aparat = obiecte[i];
$('#box tbody').append(getRow(aparat));
}
}
function getRow(aparat){
var row = '<tr>'+
'<td>' + '<p class="linkin" data-value='+aparat.id+' >'+aparat.nume+'</p>' + '</td>'+ //functia care le aranjeaza
'</tr>';
return row;
}
The problem is that when I want to get the data-value attribute like this:
$('.linkin').on('click',function(){
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function(){
console.log();
alert('success');
}
});
});
the built in paragraph works just fine, I get the data-value attribute , but the fetched paragraphs don't work, I am not able to get any attributes.
Sorry for my english.
This is happening because the event listening is only being bound to objects present when the code runs. That would explain why objects that are fetched after the code runs do not work as anticipated. This can be fixed by simply binding to the document.
$(document).on('click', '.linkin', function() {
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function() {
alert('success');
}
});
});
This is front end,
<div class="uk-width-1-4 ">
<table class="uk-table uk-table-striped uk-table-hover" id="tabledata">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>Site ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chkall" value="<%= d.siteid%>">
</td>
<td><%=d.siteid%></td>
</tr>
<% });
} %>
</tbody>
</table>
</div>
This is backend,
var user_id=req.query.user_id;
var siteid=req.query.chkall;
console.log("chkall =="+siteid);
sql="UPDATE site SET userid='"+user_id+"' WHERE siteid IN('"+siteid+"')";
}
getSQLData(sql, function(resultsets){
console.log("user...sql"+sql);
userresults = resultsets;
});
You can use it like this:
$("input[type='checkbox']").val();
Hope will help you.
If you are doing form submit, and if the check-box un-checked the false value will not go to the back-end. You should have some hidden value if check box un-checked.
If it is ajax call, you can get checkbox value as like below
$("input[type='checkbox']").val();
or
$("#checkboxid").val();
If you submit form then write name tag. And if you send data from ajax then get value by element id then send to server.
You do like this..
var chk = document.getElementById(checkboxid).checked;
if (chk == true) {
var chkval=$("#checkboxid").val();
}
If you have in list then do loop and add to a global variable and use that variable.
//check box
<asp:CheckBox ID="chkpermission" runat="server" onclick="checking(this.id);" Checked='<%# Convert.ToBoolean(Eval("permission")) %>' />
<script type="text/javascript">
function checking(id) {
$('#ctl00_ContentPlaceHolder1_lblresponce').val('');
if (id) {
ids = id.split('_');
var chkval = document.getElementById(id).checked;
var TitleId = "ctl00_ContentPlaceHolder1_grdpermissions_" + ids[3] + "_hdntitleid"; //here i am getting the value from the grid
var pagePath = window.location.pathname;
var param = JSON.stringify({ "TitleId": itleId,"chkval":chkval });
$.ajax({
type: "POST",
url: pagePath + "/updatevalue",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var result = data.d;
$('#ctl00_ContentPlaceHolder1_lblresponce').text('Updated successfully');
}
},
error: function () {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
}
</script>
in the back end code
[WebMethod]
public static Boolean updatevalue( string TitleId, string chkval)
{
Boolean flag = false;
if ( TitleId != "" && chkval !="")
{
//Update your your query here with single id...
flag=true;
// return flag if updated
}
return flag;
}
I hope it works in your case.