Limit no of rows in live search json data using $.each - javascript

I am trying to limit no of rows I am getting in live search JSON data through URL I tried counting no of table rows and return false but it doesn't work, is there any way of doing it.
$(document).ready(function() {
$.ajaxSetup({
cache: true
});
$('#search').keyup(function() {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('https://vast-shore-74260.herokuapp.com/banks?
city = MUMBAI ', function(data) {
$.each(data, function(key, value) {
var count = 0;
if ((value.city.search(expression) != -1 ||
value.branch.search(expression) != -1) && count < 10) {
$('#result').append('<tr><th>' + value.bank_name + '</th>' +
'<th>' + value.address + '</th>' +
'<th>' + value.ifsc + '</th>' +
'<th>' + value.branch + '</th>' +
'<th>' + value.bank_id + '</th></tr>'
count++;
}
else {
return false;
}
});
});
});

Try this - at least move the count=0 outside the loop
$(document).ready(function() {
$.ajaxSetup({
cache: true
});
$('#search').keyup(function() {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('https://vast-shore-74260.herokuapp.com/banks?city=MUMBAI', function(data) {
var count = 0;
$.each(data, function(key, value) {
if (count >= 10) return false;
if (value.bank_name.search(expression) != -1) {
$('#result').append('<tr><th>' + value.bank_name + '</th>' + '<th>' + value.bank_id + '</th></tr>');
count++;
}
});
});
});
});

Related

jQuery calculation of every row using multiply of quantity and price and display back on table

I'm having an issue when doing some calculation of each table row with the price and quantity. When in the console i can see the result of calculation. But when trying to display back on table it duplicate all the total sum of first row into all rows.
Here is the sample code for the part of calculation and the table display.
jQuery.ajax({
type: "POST",
url: "http://ayambrand-com-my-v1.cloudaccess.host/index.php?option=com_echarity&format=raw&task=api.get_product_name",
data: {dataArrayPost : Data},
success: function(data){
// console.log('Result process get product name' + data);
var a = JSON.parse(data);
// console.log('Result from get_product_name');
// console.log(a);
var prodName = a.productName;
var splitProductName = "";
var prodQty = a.quota;
var splitProductQuota = "";
var prodPrice = a.price;
var splitProductPrice = "";
var discountedPrice = "";
var contents = '<table id="tableDonateDisplay" class="table table-hover">';
contents += "<tr>";
contents += '<th>' + 'Product' + '</th>' + '<th>' + 'Quantity Need' + '</th>' + '<th>' + 'Price Each' + '</th>' + '<th>' + 'My Donation' + '</th>' + '<th>' + 'Amount' + '</th>';
jQuery.each(prodName, function(index1, value1) {
// console.log(prodName);
splitProductName = value1;
contents += "<tr>";
contents += '<td>' + splitProductName;
jQuery.each(prodQty, function(index, value) {
if (index1 == index) {
splitProductQuota = value;
contents += '</td><td>' + splitProductQuota;
jQuery.each(prodPrice, function(index2, value2){
jQuery.each(value2, function(index3, value3){
if(index == index2){
splitProductPrice = value3.price_value_with_tax.toFixed(2);
// console.log(splitProductPrice);
var formQuantityUpdate = "<div class='amount-controller' data-module='amount-controller'><span id='qtyminus' field='quantity' class='handle'><i class='fas fa-minus-square'></i></span><input class='input-num' type='text' id='num[]' name='number' value='0'><span id='qtyplus' field='quantity' class='handle qtyPlusHandle'><i class='fas fa-plus-square'></i></span><input type='hidden' id='pricePerProduct' name='priceHidden' value='" + splitProductPrice +"'><input type='hidden' id='maxQuantity' name='maxQuantity' value='" + splitProductQuota +"'></div>";
contents += '</td><td>' + 'RM ' + splitProductPrice + '</td>';
contents += '<td>' + formQuantityUpdate + '</td>' + '<td>' + '' + '</td>' + '<td class="eachSum">' + '' + '</td>';
contents += "</tr>";
}
});
});
}
});
});
contents += "</tr></table>";
if (jQuery('#contentNeed').html()) {
jQuery( "#contentNeed" ).empty();
}
else {
}
jQuery('#contentNeed').append(contents);
}
});
Here is the part for calculation and quantity plus minus input. The quantity will stop when it reach the quantity limits for each items.
jQuery(document).ready(function() {
var counterTotal = 0;
var quantity = 0;
var maxQuantity = 0;
jQuery(document).on('click','#qtyplus',function(e){
e.preventDefault();
fieldName = jQuery(this).attr('field');
var container = jQuery(this).parents('.amount-controller');
var currentVal = parseInt(container.children(".input-num").val());
var priceVal = parseFloat(container.children("#pricePerProduct").val());
var totalPriceCont = jQuery('.eachSum');
// totalPriceCont = jQuery('#eachSum');
maxQuantity = parseInt(container.children("#maxQuantity").val());
var val2 = currentVal + 1;
if (!isNaN(val2)) {
container.children(".input-num").val(val2);
} else {
container.children(".input-num").val(0);
}
quantity = val2;
if(quantity > maxQuantity){
quantity = maxQuantity;
container.children(".input-num").val(quantity);
return false;
}
else{
console.log('Quantity Plus :' + quantity);
counterTotal = priceVal * quantity;
totalEach = counterTotal.toFixed(2);
console.log('Sum Total Price Qty Plus : ' + totalEach);
totalPriceCont.html(parseInt(totalEach));
}
});
jQuery(document).on('click', '#qtyminus', function(e) {
e.preventDefault();
fieldName = jQuery(this).attr('field');
var container = jQuery(this).parents('.amount-controller');
var currentVal = parseInt(container.children(".input-num").val());
var priceVal = parseFloat(container.children("#pricePerProduct").val());
var totalPriceCont = jQuery('.eachSum');
// console.log(priceVal);
var val3 = currentVal - 1;
if (!isNaN(currentVal) && currentVal > 0) {
container.children(".input-num").val(currentVal - 1);
} else {
container.children(".input-num").val(0);
}
quantity = val3;
console.log('Quantity Minus :' + quantity);
console.log(currentVal);
counterTotal = priceVal * quantity;
totalEach = counterTotal.toFixed(2);
console.log('Sum Total Price Qty Minus : ' + totalEach);
totalPriceCont.html(parseInt(totalEach));
});
// totalPriceCont.html(parseInt(totalEach));
});
Results:
What am I doing wrong and how do I do this correctly?
Try initiating 'totalPriceCont' object like this:
var totalPriceCont = jQuery(this).closest('tr').find('.eachSum');

Active or Inactive on Button click in ASP.Net MVC?

I am getting return json data from server,every value is inserted in table except status.
<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
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.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>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

400 bad request while passing object and value to url

I know how to pass data in url in json or with plain parameters but this is something different
see the below image :-
http://www.tiikoni.com/tis/view/?id=23d9b98
My api Url /geniedoc/api/doctor/Search
as we can see one thing is in object and two paramater is simply passing
can you suggest me a ajax call?
my ajax call
function getNewSlotContent(startIndex, totalRows) {
var skipindex = 0;
if (startIndex > 1) {
skipindex = totalRows;
}
var totalrows = totalRows + 10;
var searchByName = document.getElementById("searchByName").value;
var selectedSpeciality = document.getElementById("searchByName").value;
if (selectedSpeciality != null || selectedSpeciality != "") {
selectedSpeciality = encodeURIComponent(selectedSpeciality);
}
$("#preloader").addClass("pageload");
$("#preloader").show();
var dataString = '{"firstName":"'+ searchByName + '","start_index":"' + skipindex + '","rows":"' + totalrows +'"}';
console.log(dataString);
$.ajax({
type: 'POST',
url : '/geniedoc/api/doctor/search',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'},
timeout: 100000,
success: function(data) {
var op = "";
for (doctor in data.response.rows) {
op += '<div class="post-sec">';
op += '<img src="/geniedoc/ajax/data/displayImage?fileName=' + data.response.rows[doctor].profilePicId + '" alt="">';
if (data.response.rows[doctor].prefix == null) {
data.response.rows[doctor].prefix = "";
}
op += '<a target="_blank" href="/doctor/' + data.response.rows[doctor].seo_name + '/' + data.response.rows[doctor].idKey + '" class="title"> ' + data.response.rows[doctor].prefix + ' ' + data.response.rows[doctor].firstame + ' ' + data.response.rows[doctor].last_name + '</a>';
op += '<span class="date">' + data.response.rows[doctor].speciality_id + '</span>';
op += '</div>';
op += '<div class="clear"></div>';
}
$("#preloader").hide();
$("#preloader").removeClass("pageload");
$("#doctor-data").html(op);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
Modify your dataString like this :
var dataString = {
"firstName":searchByName,
"start_index": skipindex,
"rows": totalrows
};

get selected row id jquery datatable row selection

i cannot get selected row id. I'm using datatable row selection. I'm getting [],[""] in console log. I have looked for other questions on SO and tried but no help
My javascript code is
$(document).ready(function () {
var selectedids = [];
var otable = $('#Table1').DataTable({
"bSort": false,
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selectedids) !== -1) {
$(row).addClass('selected');
}
}
});
$('#Table1 tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selectedids);
var ids = $.map(otable.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
if (index === -1) {
selectedids.push(id);
console.log(selectedids);
} else {
selectedids.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
I'm filling up my datatable with json data from controller in mvc
$('#ID').change(function () {
$("#t1 tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("")',
dataType: 'json',
data: { id: $("#ID").val() },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.yyy + "</td>"
+ "<td>" + item.aaa + "</td>"
+ "<td>" + item.eee + "</td>"
+ "<td>" + item.yyygg + "</td>"
+ "</tr>";
$('#Table1 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;
});
You could spare yourself a lot of pain, if you used dataTables select extension :
var table = $('#example').DataTable({
select: {
style: 'multi'
}
})
var selectedIds = [];
table.on('select.dt', function(e, dt, type, indexes) {
selectedIds.push(indexes[0]);
console.log(selectedIds);
})
table.on('deselect.dt', function(e, dt, type, indexes) {
selectedIds.splice(selectedIds.indexOf(indexes[0]), 1);
console.log(selectedIds);
})
demo -> http://jsfiddle.net/0w1p7a3s/

If / Else jQuery to skip undefined value

I have this chained select box (demo) using JSON file to populate options based on this script.
Here's the script:
$(window).bind('load', function() {
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
I have trouble using if statement to skip undefined value. The JSON file is like this:
[{"Box1":"A","Box1ID":"B","Box3":"C"},{"Box1":"E","Box1ID":"F","Box2":"G","Box3":"H"}]
If Box2 doesn't exist, I want the var $option to be:
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box3);
Would typeof undefined work here? But I'm not sure what variable should be defined.
if (typeof var?? === 'undefined') {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box3); }
else {
$("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
}
Any help would be appreciated. Thank you.
You can also just do this:
if (! data.Box2) {
...
}
Undefined, null, and empty string all test as false in JavaScript.
you can do something like:
... .text(o.Box1 + "|" + (o.Box2?oBox2+"|":"") + (o.Box3||"") );
Use
$(window).bind('load', function() {
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3);
if (typeof data.Box2 === 'undefined')
{
$option.text(o.Box1 + "|" + o.Box3);
}
else {
$option.text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
}
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
If you check the typeof of a object method/attribute that does not exists, it will return 'undefined'.

Categories

Resources