I am inputting values into an array in jQuery like 1,4,7,3. But when I am displaying the array values, it displays like 1,3,4,7.
i need like 1,4,7,3 as it is when they were inserted. This is my code.
var selectedValues = [];
var $ctrls = $("[id*=chkProcessRoutes] input:checkbox");
$("[id*=chkProcessRoutes] input:checked").each(function () {
var l = parseFloat(($ctrls.index($(this))));
var ll = parseFloat(l) + 1;
selectedValues.push(parseFloat(ll));
});
if (selectedValues.length > 0) {
alert("Selected Value(s): " + selectedValues.toString());
} else {
alert("No item has been selected.");
}
Try this:
var selectedValues = $("[id*=chkProcessRoutes] input:checked").map(function () {
return $(this).val();
});
if (selectedValues.length > 0) {
alert("Selected Value(s): " + selectedValues.toString());
} else {
alert("No item has been selected.");
}
Related
I convert an application from Core 1.1 to 2.2. Now some of my JS is not working
After conversion I noticed that my columns were no longer sorting when I clicked on them. I added some JS code and now it works. This is when I found that there was a custom JS lib with the sorting code in there but it no longer worked.
I also found that the filtering (client side) is not working.
I converted the code following the instructions in https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/?view=aspnetcore-1.1
Here is the JS script to perform the filtering.
(function ($) {
$.fn.appgrid = function appgrid() {
function configureFilter() {
$("[data-update-departments]").on("change", function () {
var triggerControl = $(this);
var connectedControl = $(triggerControl.data("update-departments"));
if (!connectedControl.data("default")) {
connectedControl.data("default", connectedControl.children());
}
var triggerValue = triggerControl.find(":selected").val();
if (triggerValue) {
$.getJSON("/ManageNomination/GetDepartments?company=" + triggerValue, function (data) {
if (data) {
connectedControl.children().remove();
connectedControl.append('<option value=""></option>');
for (var i = 0; i < data.length; i++) {
connectedControl.append('<option value="' + data[i] + '">' + data[i] + '</option>');
}
connectedControl.removeAttr("disabled");
}
});
} else {
connectedControl.children().remove();
connectedControl.attr("disabled", "disabled");
}
})
$("#applyFilter").on("click", function () {
filter = $.extend({}, defaultFilter);
$("[id^=filter-]").each(function () {
var control = $(this);
var controlId = control.attr("id").substr(7);
if (this.type === "text" || this.type === "date") {
filter[controlId] = control.val();
} else if (this.type === "select-one") {
filter[controlId] = control.find(":selected").val();
}
});
localStorage.setItem('filter', JSON.stringify(filter));
refreshData();
$("#filter-applied-message").show();
});
$(".clearFilter").on("click", function () {
filter = $.extend({}, defaultFilter);
localStorage.removeItem('filter');
localStorage.removeItem('currentPage');
refreshData();
$("#filter-applied-message").hide();
setFilterControlValues();
});
setFilterControlValues();
}
function setFilterControlValues() {
// repopulate the filter fields with the saved filter values
$("[id^=filter-]").each(function () {
var control = $(this);
var controlId = control.attr("id").substr(7);
control.val(filter[controlId] || defaultFilter[controlId] || "");
if (this.type === "select-one" && control.data("update-departments")) {
if (control.find(":selected").val()) {
// control is a connected dropdown and has a selected value
$(control.data("update-departments")).removeAttr("disabled");
} else {
$(control.data("update-departments")).attr("disabled", "disabled");
}
}
// open the filter panel automatically
//$(".filterPanel").collapse("show");
});
}
So the dropdowns for the filtering are populated but when I select a value to filter on, nothing happens.
TIA
HaYen
I have a 500+ row table and this this being filtered by as per the below code.
When someone clicks on one of the filters, I want something to show how many rows remain in the table. (And if possible for this to update everytime a new checkbox is ticked/clicked)
Can anyone help?
Apologies for the length of the code
$(document).ready(function () {
var buttons = $('#wiFilter li');
var checkboxes = $('#wiFilter input:checkbox');
$(buttons).click(function(){
var inpt = $(this).find('input');
if ($(this).is('.checked')) {
$(this).removeClass('checked');
}
else {
$(this).addClass('checked');
}
if ($(inpt).prop('checked')) {
$(inpt).removeAttr('checked').change();
}
else {
$(inpt).prop("checked", true).change();
}
$(this).blur();
});
$(checkboxes).on("change", function () {
var arrChecked = $(checkboxes).filter(':checked').map(function () {
return $(this).val();
}).get();
$("#wiTable tr:first").nextAll().show(); // reset the table: show all items
if (arrChecked.length > 0) {
$('.WI').each(function(){
var hideRow = true;
var arrCategories = $(this).text().split(', ');
for (i=0; i<arrCategories.length; i++) {
if (arrChecked.indexOf(arrCategories[i]) > -1) {
hideRow = false;
}
}
if (hideRow) {
$(this).parent().hide();
}
});
}
$(this).blur();
});
var $rows = $('#wiTable tr:first').nextAll();
$('#wiSearch').keyup(function() {
// regex looks for all words, in any order, in the text to be matched
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
str;
$rows.show().filter(function() {
str = $(this).text().replace(/\s+/g, ' '); // replace multiple spaces with one space?
return !reg.test(str);
}).hide();
});
// $('#wiSearch')
// .focus(function () {
// // $(this).val('');
// // $(countriesList).show();
// })
// .keyup(function () {
// var searchval = $(this).val().toLowerCase();
// $(countriesList).each(function () {
// if (!$(this).text().toLowerCase().match(searchval)) {
// $(this).hide();
// }
// else {
// $(this).show();
// }
// });
// })
// .blur(function () {
// var searchval = $(this).val().toLowerCase();
// if (!searchval) {
// $('#RoamingPartners_CountryListSearch').val(RoamingPartners_CountryListSearch_DefaultText);
// $(countriesList).show();
// }
// });
// $('html').bind('keypress', function(e)
// {
// if(e.keyCode == 13)
// {
// return false;
// }
// });
});
{
var x = $('#wiTable tr:visible').length;
document.getElementById("count").innerHTML = "We've got " + x + " processes that match your query";}
Many thanks in advance
https://jsfiddle.net/51Le6o06/48/
please take a look at the jsfiddle the code is getting to complicated and my functions aren't working correctly.
can anyone tell me what I could use instead of standard jQuery and javascript to make this easier to build (with a show more style pagination method).
I need to sort, filter and page existing html as in the jsfiddle.
thanks.
$(document).ready(function() {
$('.filter-gift').each(filterItems);
});
function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')
var listItems = "";
listItems += "<option value=''> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});
$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);
$('.filter-gift').change(function () {
if($(this).val()!= "") {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
} else {
$(this).parent().parent().find('table tr').show();
}
});
}
jQuery.fn.sortPaging = function(options) {
var defaults = {
pageRows: 2
};
var settings = $.extend(true, defaults, options);
return this.each(function() {
var container = $(this);
var tableBody = container.find('.internalActivities > tbody');
var dataRows = [];
var currentPage = 1;
var maxPages = 1;
var buttonMore = container.find('.seeMoreRecords');
var buttonLess = container.find('.seeLessRecords');
var buttonFree = container.find('.filter-free');
var tableRows = [];
var maxFree = 0;
var filterFree = buttonFree.is(':checked');
function displayRows() {
tableBody.empty();
var displayed = 0;
$.each(dataRows, function(i, ele) {
if( !filterFree || (filterFree && ele.isFree) ) {
tableBody.append(ele.thisRow).append(ele.nextRow);
displayed++;
if( displayed >= currentPage*settings.pageRows ) {
return false;
};
};
});
};
function checkButtons() {
buttonLess.toggleClass('element_invisible', currentPage<=1);
buttonMore.toggleClass('element_invisible', filterFree ? currentPage>=maxFreePages : currentPage>=maxPages);
};
function showMore() {
currentPage++;
displayRows();
checkButtons();
};
function showLess() {
currentPage--;
displayRows();
checkButtons();
};
function changedFree() {
filterFree = buttonFree.is(':checked');
if( filterFree && currentPage>maxFreePages ) {
currentPage=maxFreePages;
};
displayRows();
checkButtons();
};
tableBody.find('.product-data-row').each(function(i, j) {
var thisRow = $(this);
var nextRow = thisRow.next();
var amount = parseFloat(thisRow.find('.amount').text().replace(/£/, ''));
var isFree = thisRow.find('.free').length;
maxFree += isFree;
dataRows.push({
amount: amount,
thisRow: thisRow,
nextRow: nextRow,
isFree: isFree
});
})
dataRows.sort(function(a, b) {
return a.amount - b.amount;
});
maxPages = Math.ceil(dataRows.length/settings.pageRows);
maxFreePages = Math.ceil(maxFree/settings.pageRows);
tableRows = tableBody.find("tr");
buttonMore.on('click', showMore);
buttonLess.on('click', showLess);
buttonFree.on('change', changedFree);
displayRows();
checkButtons();
})
};
$('.sort_paging').sortPaging();
The best solution when it comes to tables with all the filter, sorting, pagination features and much more is one and only.
jQuery Datatables
Just check out the link, It's Easy and Highly Customizable.
Maybe you could use this jquery plug-in DataTables
I have a select list where I want to filter the options from a text input.
I wrote this jQuery code:
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if (e.text().indexOf(filterText) != -1) {
e.show();
console.log("show");
} else {
e.hide();
console.log("hide");
}
});
});
However I get the error Uncaught TypeError: e.text is not a function. I get into the each loop so there should be some option for e.
What am I doing wrong?
You must use the current value in a jQuery object to have access to the .text() method. Try:
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if ($(this).text().indexOf(filterText) != -1) {
$(this).show();
console.log("show");
} else {
$(this).hide();
console.log("hide");
}
});
});
Try to change your selector within loop :-
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if ($(e).text().indexOf(filterText) != -1) {
$(e).show();
console.log("show");
} else {
$(e).hide();
console.log("hide");
}
});
});
It may help you.
You need object variable, but accessing event variable. So please use this one
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
$(this).text()
if ($(this).text().indexOf(filterText) != -1) {
$(this).show();
console.log("show");
} else {
$(this).hide();
console.log("hide");
}
});
});
I have a Multi Select Box which contains the services and duration. If user selects some services then its duration is captured, if duration is exceed the limit then a alert is generated.How can i uncheck the last checked value by user so that duration is not reset if exceed limit.here is my code:
jQuery('.check-service').click(function () {
serviceselected = jQuery("input.check-service:checked").length;
serviceduration = 0;
jQuery('input.check-service:checked').each(function () {
serviceduration = parseInt(jQuery(this).val()) + parseInt(serviceduration);
if (selectvalues == '') {
selectvalues = jQuery(this).attr('title');
serviceids = jQuery(this).attr('id');
} else {
selectvalues = selectvalues + "," + jQuery(this).attr('title');
serviceids = serviceids + ", " + jQuery(this).attr('id');
}
});
if (serviceduration >= '600') {
alert("Selected Service is more than available time slot.");
jQuery('input.check-service').attr('checked', false);
console.log();
}
Currently its unchecked all the checked valued.I just want to uncheck the last previous selected value.
Thanks in Advance.
Try the below code:
jQuery('#CheckboxID').click(function(){ //instead of class use id
serviceselected = jQuery("input.check-service:checked").length;
serviceduration = 0;
jQuery('input.check-service:checked').each(function () {
serviceduration = parseInt(jQuery(this).val()) + parseInt(serviceduration);
if(selectvalues == '') {
selectvalues = jQuery(this).attr('title');
serviceids = jQuery(this).attr('id');
}
else {
selectvalues = selectvalues + "," + jQuery(this).attr('title');
serviceids = serviceids + ", " + jQuery(this).attr('id');
}
});
if (serviceduration >= '600') {
alert("Selected Service is more than available time slot.");
jQuery(this).attr( 'checked', false );
console.log();
}
});
You cant store last selected checkbox in some global variable.
var $lastChecked;
$(".check-service").on("change", function () {
if ($(this).attr("checked") == "checked") {
lastChecked = $(this);
}
//your logic
//...
//now when you have to uncheck:
$lastChecked.removeAttr("checked");
})