I have table rendered by js
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
Here is code
function GetCity() {
let citiesurl = '/cities/index';
$.ajax({
url: citiesurl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#cities").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info" onclick="DeleteCity()">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
}
})
}
I try to get value of cityId by button click.
Here is code
let id = $(this).closest('tr').find('.cityId').text();
But alert dhow me, that I get nothing.
Where is my error?
The problem is the context this which is not the clicked button.
Adopt the Event delegation approach for elements dynamically created:
$('#cities').on('click', 'button.btn', function() {...}
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).closest('tr').find('.cityId').text();
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
A better alternative is using the data-attributes
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button data-city-id="'+list[i].Id+'" type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).data('city-id');
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
You can modify you code the following way, using jquery:
$(document).ready(function() {
$('button').on('click', function() {
console.log($(this).data('city-id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- // these are your buttons. -->
<button data-city-id="2">Delete</button>
<button data-city-id="3">Delete</button>
<button data-city-id="4">Delete</button>
You can generate buttons something like:
'<button type="button" class="btn btn-info" data-city-id="' + list[i].Id + '">' + 'Удалить' + '</button>'
Related
In the ProdRender.js I wanna combine those three functions into one so that i do not repeat and that should match to ProdData.js as the data is in the ProdData.js and its rendering through ProdRender.js
Could someone please suggest me how to do it without repeating anything in the prodRender.js The ProdData.js seems to be working fine as i'm not repeating anything only the prodRender.js is where i'm repeating thrice.
So please help me out here
Thanks
//ProdRender.js
function ProductDataRenderer() { }
ProductDataRenderer.prototype.render = function () {
var nzd =
'<table class="table table-striped">'
+' <thead>'
+' <tr><td colspan="3">Products (NZD)</td></tr>'
+' <tr>'
+' <td>Name</td>'
+' <td>Price</td>'
+' <td>Type</td>'
+' </tr>'
+' </thead>'
+ ' <tbody>';
var n = ProductDataConsolidator.get();
for (var i = 0; i < n.length; i++) {
nzd +=
'<tr>'
+ '<td>' + n[i].name +'</td>'
+ '<td>' + n[i].price + '</td>'
+ '<td>' + n[i].type + '</td>'
+ '</tr>';
}
nzd += '</tbody></table>';
document.getElementById("nzdProducts").innerHTML = nzd;
var usd =
'<table class="table table-striped">'
+ ' <thead>'
+ ' <tr><td colspan="3">Products (USD)</td></tr>'
+ ' <tr>'
+ ' <td>Name</td>'
+ ' <td>Price</td>'
+ ' <td>Type</td>'
+ ' </tr>'
+ ' </thead>'
+ ' <tbody>';
var u = ProductDataConsolidator.getInUSDollars();
for (var i = 0; i < u.length; i++) {
usd +=
'<tr>'
+ '<td>' + u[i].name + '</td>'
+ '<td>' + u[i].price + '</td>'
+ '<td>' + u[i].type + '</td>'
+ '</tr>';
}
usd += '</tbody></table>';
document.getElementById("usdProducts").innerHTML = usd;
var euro =
'<table class="table table-striped">'
+ ' <thead>'
+ ' <tr><td colspan="3">Products (Euro)</td></tr>'
+ ' <tr>'
+ ' <td>Name</td>'
+ ' <td>Price</td>'
+ ' <td>Type</td>'
+ ' </tr>'
+ ' </thead>'
+ ' <tbody>';
var e = ProductDataConsolidator.getInEuros();
for (var i = 0; i < e.length; i++) {
euro +=
'<tr>'
+ '<td>' + e[i].name + '</td>'
+ '<td>' + e[i].price + '</td>'
+ '<td>' + e[i].type + '</td>'
+ '</tr>';
}
euro += '</tbody></table>';
document.getElementById("euProducts").innerHTML = euro;
}
//ProdData.js
function ProductDataConsolidator() { }
ProductDataConsolidator.get = function (currency) {
var l = new LawnmowerRepository().getAll();
var p = new PhoneCaseRepository().getAll();
var t = new TShirtRepository().getAll();
const arr_names = [
[l, "lawnmower"],
[p, "Phone Case"],
[t, "T-Shirt"],
]
var products = [];
let multiplier = currency == "euro"
? 0.67
: currency == "dollar"
? 0.76
: 1;
for (let [arr,name] of arr_names){
for (var i = 0; i < arr.length; i++) {
products.push({
id: arr[i].id,
name: arr[i].name,
price: (arr[i].price * multiplier).toFixed(2),
type: name
});
}
}
return products;
}
ProductDataConsolidator.getInEuros = function(){
return ProductDataConsolidator.get("euro");
}
ProductDataConsolidator.getInUSDollars = function(){
return ProductDataConsolidator.get("dollar");
}
You need to break it down to smaller functions and parameterise them
const table = (currency, content) =>
`<table class="table table-striped">
<thead>
<tr><td colspan="3">Products (${currency})</td></tr>
<tr>
<td>Name</td>
<td>Price</td>
<td>Type</td>
</tr>
</thead>
<tbody>
${content}
</tbody>
</table>`
;
const table_content = data =>
data.map(({ name, price, type }) =>
`<tr>
<td>${name}</td>
<td>${price}</td>
<td>${type}</td>
</tr>`)
.join('\n')
;
const currencyCode = {
dollar: 'USD',
euro: 'Euro',
newZealand: 'NZD'
};
function ProductDataRenderer() { }
ProductDataRenderer.prototype.render = function (currency, target) {
const productData = ProductDataConsolidator.get(currency);
const html = table(currencyCode[currency], table_content(productData));
document.getElementById(target).innerHTML = html;
}
I didn't change the design of your code but you can see render does 3 different things. It should only render, not also retrieve data and inject the table in the DOM.
It makes also little sense to have one ProductDataConsolidator with three static methods having different names. Either you create 3 derivatives of ProductDataConsolidator with only one method get each and you pass an instance of the right derivative to render so that it only needs to know about one method named get (by the way if you have one object with only one method it's a function so why bother use an object), or you pass the product data directly to render (preferred)
hello i am trying to add table in division when date is shown ...all perform okay ..but in division an unwanted code generate like [object Object],[object Object]...i want to remove that code.
$(document).ready(function () {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
$('#DT').val(today);
$.fn.ABC = function () {
var selectedValue = $("#DT").val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWaxAss")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'SelectedDate': selectedValue }),
success: function (waxAsslist) {
if (Object.keys(waxAsslist).length > 0) {
$('#detailtbl').text("");
$('#detailtbl').append('<div class="card">' +
'<div class="card-header card-header-primary card-header-icon">' +
'<div class="card-icon"><i class="material-icons">assignment</i>' +
'</div><h4 class="card-title">Wax Assembly List</h4></div>' +
'<div class="card-body">' +
'<div class="material-datatables">' +
'<table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">' +
'<thead>' +
'<tr>' +
'<th><b>PRC No</b></th>' +
'<th><b>Die No</b></th>' +
'<th><b>Description</b></th>' +
'<th><b>Metal</b></th>' +
'<th><b>Qty</b></th>' +
'<th><b>Reject Qty</b></th>' +
'<th><b>Shell</b></th>' +
'<th><b>Total Weight</b></th>' +
'<th><b>User</b></th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
$.each(waxAsslist, function (i, data) {
setTimeout(function () {
$('#datatables tbody').append(
'<tr>'
+ '<td>' + data.PRCNO + '</td>'
+ '<td>' + data.MOULDCODE + '</td>'
+ '<td>' + data.DESCRIPTION + '</td>'
+ '<td>' + data.METALNAME + '</td>'
+ '<td>' + data.Qty + '</td>'
+ '<td>' + data.RejectQty + '</td>'
+ '<td>' + data.Shell + '</td>'
+ '<td>' + data.TotalWt + '</td>'
+ '<td>' + data.USERNAME + '</td>'
+ '</tr>'
)
}, 1000);
}),
'</tbody>' +
'</table>' +
'</div>' +
'</div>' +
'</div>');
}
},
error: function () { alert('Error. Please try again.'); }
});
};
$.fn.ABC();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<input type="date" id="DT">
</div>
<div class="row">
<div class="col-md-12" id="detailtbl">
</div>
</div>
here is my controller where from my data came.
[HttpPost]
public ActionResult DateWiseData(DateTime SelectedDate)
{
var Dw = DateTime.Now.ToShortDateString();
var idparam = new SqlParameter
{
ParameterName = "date",
Value = SelectedDate
};
var waxAsslist = Db.Database.SqlQuery<spDataWaxAss>("exec sp_PRCWax_Assembly_Get_Date #date", idparam).ToList();
return Json(waxAsslist, JsonRequestBehavior.AllowGet);
}
return json value like this
json return value
in output it will be show like this ...
output generate like this
i want to remove yellow highlighted portion ...i don't know from where it generate...
can any one help me..
My js function is
function view_customerTOTable(){
var name = $('#name').val();
//alert(name);
$.ajax({
type: 'post',
url: 'viewCustomerData',
data: name,
success: function (data) {
alert('test'+data);
var result = JSON.parse(data);
var datas = [];
for (var x = 0; x < result.length; x++) {
datas.push('<tr id="op' + x + '">'
+ '<td hidden="true">' + result[x].C_email + '</td>'
+ '<td>' + result[x].C_clientint + '</td>'
+ '<td align="center">' + result[x].C_status + '</td>'
+ '<td align="center">' + result[x].C_clientcode + '</td>'
+ '<td align="center">' + result[x].C_name + '</td>'
+ '<td align="right">' + result[x].C_nic + '</td>'
+ '<td align="center">'
+ '<input type="button" class="btn btn-warning" value="view">'
+ '</td>'
+ '</tr>');
}
$j('#bdy_customer_details').html(datas);
//alert(data);
},
error: function(){
alert('error');
}
});
}
controller function is
function viewCustomerData(){
$this->load->model('customer/customer_model');
echo json_encode($this->customer_model->loadCustomerDetails());
}
the values return from this modle function
function loadCustomerDetails(){
//$query = $this->db->select('*')->from('customer');
$sql = "SELECT * FROM customer where C_name = '{$_POST['name']}'";
//$send = $query->mod_select();
try {
return $this->db->select($sql);
} catch (Exception $exc) {
return $exc->getTraceAsString();
}
}
view page is
<table id="customer_details" class="table table-bordered" cellspacing="1" cellpadding="1" width="100%" >
<thead>
<tr>
<td><font type="curlz MT Regular" color="black">Asset Type</font></td>
<td><font type="curlz MT Regular" color="black">Client Code</font></td>
<td><font type="curlz MT Regular" color="black">Contract No</font></td>
<td><font type="curlz MT Regular" color="black">Contract Name</font></td>
<td><font type="curlz MT Regular" color="black">Customer Name</font></td>
<td><font type="curlz MT Regular" color="black">NIC No.</font></td>
<td><font type="curlz MT Regular" color="black">View</font></td>
<!--<td>Remove</td>-->
</tr>
<thead>
<tbody id="bdy_customer_details" >
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td id="tdet1"></td>
<td id="tdet2"></td>
<td id="tdet3"></td>
</tr>
</tfoot>
</table>
i want to display those data in table. but i cant return data. in js function function move to success point. but json.parse point it not works
in your controller action change below code. here in your code you are not return data from model. it return only test.
die(json_encode(array('result' => 'test')));
//as per updated question
die(json_encode($this->customer_model->loadCustomerDetails()));
remove this header
header('Content-Type: application/json');
updated javascript code
var result = JSON.parse(data);
var datas = '';
for (var x = 0; x < result.length; x++) {
datas = '<tr id="op' + x + '">'
+ '<td hidden="true">' + result[x].C_email + '</td>'
+ '<td>' + result[x].C_clientint + '</td>'
+ '<td align="center">' + result[x].C_status + '</td>'
+ '<td align="center">' + result[x].C_clientcode + '</td>'
+ '<td align="center">' + result[x].C_name + '</td>'
+ '<td align="right">' + result[x].C_nic + '</td>'
+ '<td align="center">'
+ '<input type="button" class="btn btn-warning" value="view">'
+ '</td>'
+ '</tr>';
// if((result.length - 1) === x){
$('#bdy_customer_details').append(datas);
//}
}
I am new in Bootstrap JS. I have a table made with Bootsrap JS, whose data came from a Json file. Here is The Code-
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="fixedscroll">
<table id="user_table" class="table table-hover table-bordered table-striped responsive" style="margin-bottom: 0;" class="display">
<thead>
<tr>
<th>UID</th>
<th>Name</th>
<th>Address</th>
<th>Tags</th>
<th>Edit tags</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
function showAll(){
$.ajax({
url: "showAll",
dataType:"json",
success:function(data){
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function(index, value) {
var row = '<tr>'
+ '<td id="tduid">'+ value['uid']+ '</td>'
+ '<td>'+ value['name']+ '</td>'
+ '<td>'+ value['address']+ '</td>'
+ '<td>'+ value['tag1']+ ',' + value['tag2']+ ',' + value['tag3']+'</td>' + '<td>'+ '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
Now This Payload is the name of my json, which came from a servlet where I call the database.
Now let, there is 3 tags. But some of rows have 2 tags. So, when I put the values in json the Json looks like-
{"Payload":[{"uid":"u01","name":"Subho","address":"Dumdum","tag1":"aircel","tag2":"vodafone","tag3":"airtel"},{"uid":"u02","name":"Jeet","address":"Baruipur","tag1":"airtel","tag2":"","tag3":"aircel"},{"uid":"u03","name":"Diba","address":"Jadavpur","tag1":"vodafone","tag2":"aircel","tag3":"airtel"},{"uid":"u04","name":"Tommy","address":"Baguihati","tag1":"aircel","tag2":"vodafone","tag3":""},{"uid":"u05","name":"Jonty","address":"Rahara","tag1":"","tag2":"vodafone","tag3":"airtel"},{"uid":"u06","name":"Gourav","address":"Tripura","tag1":"aircel","tag2":"vodafone","tag3":"airtel"}]}
Now You can see, that for UID=U02 there is 2 tags. And the output looks like picture attached. How can I remove the blank values or null values???? Please anyone help me...
I think, you are saying about the extra , in the tags column... one messy solution is
$.ajax({
url: "showAll",
dataType: "json",
success: function (data) {
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function (index, value) {
var tags = $.map([value.tag1, value.tag2, value.tag3], function (value) {
return value || undefined;
});
var row = '<tr>' + '<td id="tduid">' + value['uid'] + '</td>' + '<td>' + value['name'] + '</td>' + '<td>' + value['address'] + '</td>' + '<td>' + tags + '</td>' + '<td>' + '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
As #Alnitak said
var tags = [value.tag1, value.tag2, value.tag3].filter(function (value) {
return value !== undefined;
});
console.log(tags)
I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>