May be it will be a very easy question some of expert but seems difficult to me. I want to use a variable in pattern of regular expression.
$("#srcbtn .btnPage").live("click",function(){
var filter = $(this).val(), count = 0;
$(".checkpoint").each(function () {
if ($(this).find(".chpdetails .chkpname").text().search(new RegExp(/\b filter /i)) < 0) {
$(this).hide();
} else {
$(this).show();
count++;
}
});
});
but the filter variable doesn't work in if condition. the purpose of this code is to search a word which is start with filter variable's value i.e. A, B etc. How can i do this?
Thanks in advance.
Use this :
new RegExp("\\b" + filter, 'i')
See the documentation on RegExp
If you have many checkpoints, you should probably build the regexp object before entering the loop instead of building it at each iteration :
var r = new RegExp("\\b" + filter, 'i');
$(".checkpoint").each(function () {
if ($(this).find(".chpdetails .chkpname").text().search(r) < 0) {
$(this).hide();
} else {
$(this).show();
count++;
}
});
Using the constructor allows this for RegExp
$("#srcbtn .btnPage").live("click",function(){
var filter = $(this).val(), count = 0;
$(".checkpoint").each(function () {
if ($(this).find(".chpdetails .chkpname").text().search(new RegExp("\\b" + filter, "i")) < 0) {
$(this).hide();
} else {
$(this).show();
count++;
}
});
});
Related
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;
});
I have a plugin that is cloning an input that may or may not have the jQuery validation engine bound to it.
so, it's classes may contain e.g. validate[required,custom[number],min[0.00],max[99999.99]] or any combination of the jQuery validation engine validators.
The only for sure thing is that the class begins with validate[ and ends with ], but to make it more complicated as in the example above, there can be nested sets of [].
So, my question is, how can I remove these classes (without knowing the full class) using jQuery?
Here is my implementation, It's not using regex, but meh, who said it had too?
//'first validate[ required, custom[number], min[0.00], max[99999.99] ] other another';
var testString = $('#test')[0].className;
function removeValidateClasses(classNames) {
var startPosition = classNames.indexOf("validate["),
openCount = 0,
closeCount = 0,
endPosition = 0;
if (startPosition === -1) {
return;
}
var stringStart = classNames.substring(0, startPosition),
remainingString = classNames.substring(startPosition),
remainingSplit = remainingString.split('');
for (var i = 0; i < remainingString.length; i++) {
endPosition++;
if (remainingString[i] === '[') {
openCount++;
} else if (remainingString[i] === ']') {
closeCount++;
if (openCount === closeCount) {
break;
}
}
}
//concat the strings, without the validation part
//replace any multi-spaces with a single space
//trim any start and end spaces
return (stringStart + remainingString.substring(endPosition))
.replace(/\s\s+/g, ' ')
.replace(/^\s+|\s+$/g, '');
}
$('#test')[0].className = removeValidateClasses(testString);
It might actually be simpler to do that without JQuery. Using the className attribute, you can then get the list of classes using split(), and check whether the class contains "validate[".
var classes = $('#test')[0].className.split(' ');
var newClasses = "";
for(var i = 0; i < classes.length; i++){
if(classes[i].indexOf('validate[') === -1){
newClasses += classes[i];
}
}
$('#test')[0].className = newClasses
I think this solution is even more simple. You just have to replace field_id with the id of that element and if the element has classes like some_class different_class validate[...] it will only remove the class with validate, leaving the others behind.
var that ='#"+field_id+"';
var classes = $(that).attr('class').split(' ');
$.each(classes, function(index, thisClass){
if (thisClass.indexOf('validate') !== -1) {
$(that).removeClass(classes[index])
}
});
I have created a game that is based on a grid being populated with words
In my code I have a small bit of underscore.js that helps my words fit in the space available in the grid without breaching the grids barriers.
I understand that it is very powerful java script and don't personally have a problem with it. But my team manager would like to get rid of it for some jQuery that will provide the same solution as there is only one function and would save me having a whole library. How I would replace this with some jQuery?
function getWordToFitIn(spaceAvail, wordlist) {
var foundIndex = -1;
var answer = _.find(wordlist, function (word, index) {
if (word.length <= spaceAvail) {
foundIndex = index;
return true;
}
});
if (foundIndex == -1) {
answer = getXSpaces(spaceAvail);
_.find(wordlist, function (word, index) {
if (word[0] == " ") {
foundIndex = index;
return true;
}
});
}
if (foundIndex != -1) {
wordlist.splice(foundIndex, 1);
}
return answer;
}
As far as I can see, the only underscore method youre using is _.find. But I don’t think you are using it as it was intended. It looks like you are simply looping and returning true when a criteria is met.
You can use the native forEach if you don’t have legacy support, or use a shim. Or you can use the jQuery.each method.
The first loop could probably (I’m not 100% sure about the answer variable) be written like this:
var answer;
$.each(wordlist, function(index, word) {
if (word.length <= spaceAvail) {
foundIndex = index;
answer = word;
return false; // stops the loop
}
});
And the second one:
$.each(wordlist, function (index, word) {
if (word[0] == " ") {
foundIndex = index;
return false;
}
});
I have had some help on a Jquery script which creates a searchable, toggleable FAQ. The code can be seen here:
http://jsfiddle.net/pT6dB/62/
The trouble is, if there is the word “How” with an upper case “H” and I search “h”, it wont find it. How can I make this script case insensitive?
Update
Alternatively, you could reduce the amount of code significantly using regular expression. jsFiddle demo
$('#search').keyup(function(e) {
// create the regular expression
var regEx = new RegExp($.map($(this).val().trim().split(' '), function(v) {
return '(?=.*?' + v + ')';
}).join(''), 'i');
// select all list items, hide and filter by the regex then show
$('#result li').hide().filter(function() {
return regEx.exec($(this).text());
}).show();
});
Original
Based on your current algorithm for determining relative elements, you could use the jQuery filter method to filter your results based on the keywords array. Here's a rough idea:
// select the keywords as an array of lower case strings
var keywords = $(this).val().trim().toLowerCase().split(' ');
// select all list items, hide and filter then show
$('#result li').hide().filter(function() {
// get the lower case text for the list element
var text = $(this).text().toLowerCase();
// determine if any keyword matches, return true on first success
for (var i = 0; i < keywords.length; i++) {
if (text.indexOf(keywords[i]) >= 0) {
return true;
}
}
}).show();
Change this line
$('#result LI:not(:contains('+keywords[i]+'))').hide();
to
$('#result LI').each(function()
{
if(this.innerHTML.toLowerCase().indexOf(keywords[i].toLowerCase()) === -1)
{
$(this).hide();
}
});
// split the search into words
var keywords = s.toLowerCase().split(' ');
// loop over the keywords and if it's not in a LI, hide it
for(var i=0; i<keywords.length; i++) {
$('#result LI').each(function (index, element) {
if ($(element).text().toLowerCase().indexOf(keywords) != -1) {
$(element).show();
} else {
$(element).hide();
}
});
}
I have a three strings of categories
"SharePoint,Azure,IT";
"BizTalk,Finance";
"SharePoint,Finance";
I need to find a way to check if a string contains for example "SharePoint" and "IT", or "BizTalk" and "Finance". The tests are individual strings themselces.
How would i loop through all the category strings (1 - 3) and only return the ones which have ALL instances of the souce.
i have tried the following
function doesExist(source, filterArray)
{
var substr = filterArray.split(" ");
jQuery.each(substr, function() {
var filterTest = this;
if(source.indexOf(filterTest) != -1 )
{
alert("true");
return true;
}else
{
alert("false");
return false;
}
});
}
with little success...the code above checks one at a time rather than both so the results returned are incorrect. Any help would be great.
Thanks
Chris
UPDATE: here is a link to a work in progress version..http://www.invisiblewebdesign.co.uk/temp/filter/#
Try this:
function doesExist(source, filter)
{
var sourceArray = source.split(",");
var filterArray = filter.split(",");
var match = true;
$.each(filterArray, function(i, val) {
match = match && ($.inArray(val, sourceArray) != -1);
});
return match;
}
gives doesExist("SharePoint,Azure,IT", "SharePoint,IT")==true but doesExist("SharePoint,Azure,IT", "SharePoint,BizTalk")==false.
you could try something like:
if(filterArray.indexOf("SharePoint") > -1 && filterArray.indexOf("IT") > -1) {
...
}