jQuery .hide(), then .show() based on text input - javascript

Using a jQuery filter example I found. Here is my live example. Here is the CodePen, (also the Fiddle if you don't like CodePen).
After typing something in the input, the boxes do realign and the numbers dissapear. However, when you delete the text you inputted, the numbers do not reappear unless you refresh the page. I tried messing around with the code below but wasn't having any luck. Thanks for you help!
$('#sortable').change(
function(){
if ($(this).val().length) {
$('#number').hide();
}
else {
$('#number').show();
}
});

Try this out:- http://jsfiddle.net/adiioo7/nYYBU/10/
JS:-
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var list = $("#sortable");
var filter = $(this).val();
console.log(filter.length);
if (filter.length > 0) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(".number").hide();
$(".numberstwo").hide();
} else {
console.log($(".number"));
$(".number").show();
$(".numberstwo").show();
$(list).find("a").parent().slideDown();
}
return false;
}).keyup(function () {
$(this).change();
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));

Here's updated js...
Checkout Demo Fiddle
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var filter = $(this).val();
if (filter) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
}).keyup(function () {
$(this).change();
if ($(this).val().length) {
$('.number').hide();
} else {
$('.number').show();
}
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));

To check the entered text I normally use keyup.
Change is not triggered when the user types something but when he types and exits the box.

$('#sortable').blur(function(){
var len = $(this).val().length;
if (len) {
$('#number').hide();
}
else {
$('#number').show();
}

Related

How to fix Javascript no longer working after converting to core 2.2

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

how to convert functions into a JQuery plugin

I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()

Show No record message for search on textbox

I have a textbox which I use for filtering gridview. IT filters properly whenever I add proper text. But when I dont add proper text what I want is to show some alert as, Invalid Record.
Below is my code
$(function () {
$('.field-style').each(function (i) {
$(this).quicksearch("[id*=grdSapDetails] tr:not(:has(th))", {
'testQuery': function (query, txt, row) {
return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
}
});
});
});
Please suggest what to do
UPDATE
I have added my alert message in noResults like below in quicksearch.js but still it is not giving alert.
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 100,
selector: null,
stripeRows: null,
loader: null,
noResults: 'tr#noresults',
matchedResultsCount: 0,
bind: 'keyup',
onBefore: function () {
return;
},
You can use the Jquery to search the Grid View and based on the Row Filter count you can show the alert message:
function SearchGrid(txtSearchSAP, grdSapDetails) {
if ($("[id *=" + txtSearchSAP + " ]").val() != "") {
var count = 0;
$("[id *=" + grdSapDetails + " ]").children
('tbody').children('tr').each(function () {
$(this).show();
});
$("[id *=" + grdSapDetails + " ]").children
('tbody').children('tr').each(function () {
var match = false;
$(this).children('td').each(function () {
if ($(this).text().toUpperCase().indexOf($("[id *=" +
txtSearchSAP + " ]").val().toUpperCase()) > -1) {
match = true;
count++;
return false;
}
});
if (match) {
$(this).show();
$(this).children('th').show();
}
else {
$(this).hide();
$(this).children('th').show();
}
});
$("[id *=" + grdSapDetails + " ]").children('tbody').
children('tr').each(function (index) {
if (index == 0)
{
$(this).show();
}
});
if(count==0)
{
alert("No Matching Records");
}
}
else {
$("[id *=" + grdSapDetails + " ]").children('tbody').
children('tr').each(function () {
$(this).show();
count=0;
});
}
}
$(document).on("keyup", function () {
SearchGrid('txtSearchSAP', 'grdSapDetails');
});
Here is the working Fiddle
I can't understand how are you merging server side and client side code.
You are talking about server control (GridView) so you can use the EmptyDataText property.
https://msdn.microsoft.com/it-it/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
Client side you can work on document ready: counting visible rows and showing a message.

jQuery filter select options by text input

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");
}
});
});

Conflict with counting filled fields with input hints. Any work around?

I have a script to count the number of fields that are filled. Works great. But I discovered the script only counts the fields that DO NOT have input hints. Is there any work around?
http://jsbin.com/oguzaj/4
SCRIPT TO COUNT FIELDS:
$(document).ready(function () {
(function ($) {
$('#form_register').on('keyup change', function () {
var number = 0;
$(this).find('input, textarea').each(function () {
if (this.value !== '') {
$('.input_count').val(number++);
}
});
});
})(jQuery);
});
SCRIPT FOR INPUT HINTS:
(function ($) {
$.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur';
}
return this.each(function () {
var $input = $(this),
title = $input.attr('title'),
$form = $(this.form),
$win = $(window);
function remove() {
if ($input.val() === title && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass);
}
}
if (title) {
$input.blur(function () {
if (this.value === '') {
$input.val(title).addClass(blurClass);
}
}).focus(remove).blur();
$form.submit(remove);
$win.unload(remove);
}
});
};
})(jQuery);
$(function () {
$('input[title!=""]').hint();
$('textarea[title!=""]').hint();
});
$(document).ready(function() {
$('#form_register').on('keyup change', function() {
var number = 0;
$(this).find('input, textarea').each(function() {
if ($(this).val() && !$(this).hasClass('blur')) {
$('.input_count').val(number++);
}
});
});
});
Edit:
If you've got an button which fills one field you'll need to add this to the button.
$(buttonSelector).on('click', function() {
var number = 0;
$('#form_register').find('input, textarea').each(function() {
if ($(this).val() && !$(this).hasClass('blur')) {
$('.input_count').val(number++);
}
});
});

Categories