Searching table rows with jQuery Non-Case sensitive [duplicate] - javascript

This question already has answers here:
Is there a case insensitive jQuery :contains selector?
(12 answers)
Closed 9 years ago.
I am trying out this nice little jQuery script for searching tables found here:
Searching table rows with jQuery
It works great, however I don't want it to be case sensitive, for example if a value in my table is Value One, I want to be able to search value one, or VALUE ONE and still get the right outcome.
This is the Jquery that controls it:
<script>
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
var searchterm = $(this).val();
if(searchterm.length > 3) {
var match = $('tr.data-row:contains("' + searchterm + '")');
var nomatch = $('tr.data-row:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.css("display", "none");
} else {
$('tr.data-row').css("display", "");
$('tr.data-row').removeClass('selected');
}
});
});
</script>
Can anyone help me with making it non case sensitive?

You can turn both strings into lowercase with the toLowerCase() method.
It should look something like this:
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
var searchterm = $(this).val();
searchterm=searchterm.toLowerCase();
if(searchterm.length > 3) {
var match = $('tr.data-row:contains("' + searchterm + '")');
var nomatch = $('tr.data-row:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.css("display", "none");
} else {
$('tr.data-row').css("display", "");
$('tr.data-row').removeClass('selected');
}
});
});
And you will need to override the jQuery method too! Something that looks like this...
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toLowerCase().indexOf(arg.toLowerCase()) >= 0;
};
});
It is pretty straight forward, all that you're doing is forcing both strings to be lower case before comparing them. That way you skip the different cases issue.
Hope this helps, good luck.

Your best best might be to write your own selector expression like this:
$.expr[":"].containsCI = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});

You can find the solution here : Link , this will override the orginal ":contains" selector
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});

Related

Remove case sensitivity in a JS search [duplicate]

This question already has answers here:
Contains case insensitive
(14 answers)
Closed 3 years ago.
I have a list on a page and a search bar that searches and filters the list as the user types. At the moment the input has to be all lowercase (which I've added myself). How can I remove all case sensitivity from the search string? For example if I search for teST the result for Test would still appear.
var list = $("table.ms-listviewtable");
var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
var input = $("input#filterInput");
input.keyup(function() {
listItems.each(function() {
var text = $(this).text();
var text = $(this).text().toLowerCase();
if (text.indexOf(input.val()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
Just use toLowerCase on input.val() as well as text.
if (text.indexOf(input.val().toLowerCase()) != -1) {...}
Also note you can use includes instead of indexOf on newer browsers:
if (text.includes(input.val().toLowerCase())) {...}
You can also use the .match method
var list = $("table.ms-listviewtable");
var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
var input = $("input#filterInput");
input.keyup(function() {
let inputVal = input.val().toLowerCase();
listItems.each(function() {
if($(this).text().toLowerCase().match(inputVal)){
$(this).show();
} else {
$(this).hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

javascript to jQuery or vice versa

I can just about struggle through with jquery, javascript less so.
I have a small function written in javascript, but I need to change the selectors. I wouldn't have any problem in doing this in jquery, but I do in js.
I need help either: converting my selector to its js equivalent, or converting the function in its entirety to jquery (as its only 4 lines of code).
function findNextTabStop() {
// This is the current selector
var universe = document.querySelectorAll("input");
// In jQuery, the NEW selector would look like this
$universe = $(this).closest(".form").find(".input-wrapper input, .input-wrapper select, .input-wrapper textarea");
var list = Array.prototype.filter.call(universe,
function (item) {
return item.tabIndex >= "0"
});
var index = list.indexOf(this);
return list[index + 1] || list[0];
}
After a bit of digging and testing, this is what I've come up with
function findNextTabStop() {
$el = $(this).closest(".input-step").find(inputs);
var index = $el.index(this);
return $el[index + 1] || $el[0];
}

Using JavaScript to cycle through elements with numbers in the ID [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I'm interested in cycling through some div's I have on my page that have numbers in the ID.
This is what I have so far...
var count = 1;
while(count != 12) {
$('#logo-'.concat(count).concat(' > img')).click(function() {
if($('#info-'.concat(count)).hasClass('dropdown-active')) {
$('#info-'.concat(count)).slideUp();
$('#info-'.concat(count)).removeClass('dropdown-active');
} else {
$('#info-'.concat(count)).slideDown();
$('#info-'.concat(count)).addClass('dropdown-active');
}
return false;
});
count++;
}
The count seems to stop working when it reaches the if statement.
So the ID's on the page are logo-1, info-1, logo-2, info-2, etc...
You can do this more cleanly as follows:
while(count != 12) {
$('#logo-' + count + ' > img').click(function() {
var origin = $(this).parent(),
targetId = '#info-' + origin[0].id.substring(5),
target = $(targetId);
if(target.hasClass('dropdown-active')) {
target.slideUp();
target.removeClass('dropdown-active');
} else {
target.slideDown();
target.addClass('dropdown-active');
}
return false;
});
count++;
}
But it would be preferable to give all your logos the same class (say, "logo"), and then you can ditch the while loop:
$('.logo > img').click(function() {
var origin = $(this).parent(),
targetId = '#info-' + origin[0].id.substring(5),
target = $(targetId);
if(target.hasClass('dropdown-active')) {
target.slideUp();
target.removeClass('dropdown-active');
} else {
target.slideDown();
target.addClass('dropdown-active');
}
});
Edit: As Karl-André Gagnon points out in the comments, you could also use $('[id^="logo-"]') as an alternative to giving them a class, and still use the no-while-loop approach.
One alternative to parsing the numbers out of the IDs would be to store the number in a data-num attribute:
<div class='logo' data-num='1'>...</div>
And then instead of that var origin... stuff with the substring method, you would have:
var num = $(this).parent().data('num'),
target = $('#info-' + num);
While JLRishe's answer is preferable, here's a largely academic demonstration of doing it with closures:
var count = 1;
while(count != 12) {
(function(id){
$('#logo-'.concat(id).concat(' > img')).click(function() {
if($('#info-'.concat(id)).hasClass('dropdown-active')) {
$('#info-'.concat(id)).slideUp();
$('#info-'.concat(id)).removeClass('dropdown-active');
} else {
$('#info-'.concat(id)).slideDown();
$('#info-'.concat(id)).addClass('dropdown-active');
}
return false;
});
}(count));
count++;
}
By calling a function and passing the value as a parameter, you create a new scope and thus id will maintain it's value in the click function. I wouldn't necessarily recommend this approach (there are many inefficiencies in your code besides), but hopefully it's an interesting demonstration of closures and scope.

Dynamic event attachment not working correctly [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
var smartActionsId = ['smartActions1','smartActions5','smartActions10'];
for (var i in smartActionsId) {
console.log("smartActionsId ="+smartActionsId[i]);
$('#' + smartActionsId[i] + ' select').change(function () {
var value = $(this).val();
var disableValue;
var ruleIndex = smartActionsId[i].substr(11);
console.log("smartActionsId ="+smartActionsId[i]+" i ="+i);
if (value === '0') {
disableValue = true;
onRuleToggle(disableValue, ruleIndex)
}
else if (value === '1') {
disableValue = false;
onRuleToggle(disableValue, ruleIndex)
}
});
}
I'm creating change event dynamically for a multiple switch slider items using the above JavaScript code. But problem I'm facing is, when I click on any switch 'i' value gets replaced with the last value i.e. in smartActionsId I have 3 elements, which ever switch I change it effects for last switch (smartActions10).
Could you please help me resolving this issue?
Other answers here fixed your problem, but I think you can refactor your code a little and make it much more understandable.
First, I don't like IDs. in your scenario, you have multiple ids which needs to be treated the same. Why not use one mighty class?
Also, ruleIndex calculated from element's ID? smells rotten.
If it tells you something about the element, it should be in an attribute or a data-* attribute.
The first bit of code fixes the markup by adding ruleIndex as data attribute and adding a .smart-actionable class. (Maybe you can even move this part to the server-side, to provide yourself with easier markup for JS).
Now, this makes the event handling quite simple.
var smartActionsId = ['smartActions1','smartActions5','smartActions10'];
for (var i in smartActionsId) {
$('#' + smartActionsId[i])
.data('ruleIndex', smartActionsId[i].substr(11))
.addClass('smart-actionable');
}
$('.smart-actionable').on('change', 'select', function() {
var value = $(this).val();
var disableValue = (value === '0');
onRuleToggle(disableValue, $(this).data('ruleIndex'));
});
Hope it will help.
You don't want to attach event listeners inside a for loop because the variable that tracks the index is used by each loop cycle. If you do that, the i variable will always equal the length of the array minus 1. Use Array.prototype.forEach() instead to prevent that.
var smartActionsId = ['smartActions1','smartActions5','smartActions10'];
smartActionsId.forEach(function (identifier, index) {
console.log("smartActionsId ="+identifier);
$('#' + smartActionsId[index] + ' select').change(function () {
var value = $(this).val();
var disableValue;
var ruleIndex = smartActionsId[index].substr(11);
console.log("smartActionsId ="+smartActionsId[index]+" index ="+index);
if (value === '0') {
disableValue = true;
onRuleToggle(disableValue, ruleIndex)
}
else if (value === '1') {
disableValue = false;
onRuleToggle(disableValue, ruleIndex)
}
});
});
Please Note: IE8 and down does NOT support Array.prototype.forEach().
You cant use for...in in this case. Please try the code below:
var smartActionsId = ['smartActions1', 'smartActions5', 'smartActions10'];
for (var i = 0; i < smartActionsId.length; i++) {
console.log("smartActionsId =" + smartActionsId[i]);
$('#' + smartActionsId[i] + ' select').change(function() {
var value = $(this).val();
var disableValue;
var ruleIndex = smartActionsId[i].substr(11);
console.log("smartActionsId =" + smartActionsId[i] + " i =" + i);
if (value === '0') {
disableValue = true;
onRuleToggle(disableValue, ruleIndex)
} else if (value === '1') {
disableValue = false;
onRuleToggle(disableValue, ruleIndex)
}
});
}
I've always use names like smartActions_1. If you can use it, then in your .change function you can use
// if 'smartActionsId' is global variable
// and if you need to get position in 'smartActionsId' array
var numInArray = $.inArray( this.parentNode.id, smartActionsId );
// this - your select DOM object
var ruleIndex = parseInt( this.parentNode.id.split( "_" )[ 1 ] );
And remember that this in .change function its select which have no id and you must use this.parentNode or $( this ).parent() to get it's holder (I think its div or somethink like that).
#Jack in comments is right: select may not be a direct child. Then you can use this code:
var parent = $( this ).closest( "[id^=smartActions]" );
var numInArray = $.inArray( parent.attr( "id" ), smartActionsId );
var ruleIndex = parseInt( parent.attr( "id" ).split( "_" )[ 1 ] );

How to find if a value matches one of the values from an array in Javascript [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});

Categories

Resources