How to get the array index of an #name from an input? - javascript

I have a textarea and a dropdown set. I have it set so if a user does #name (or anything) it will display a dropdown list of users with specified input. I don't know how to do the regex for searching an array for an #name within it.
Example: User types "Hi #bob", then array is ["Hi","#bob"];
How do I find where #bob is and if a user hit spaces afterwords, the regex detects if a space is placed right after it.
example code I have tried
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 64) { //Enter keycode
$('.postingArea').on("keyup", function(){
var inputVal = $(this).val();
var res = inputVal.split(" ");
console.log(jQuery.inArray( "#/w/", res ));
var myString = inputVal.match(/#([^ ]*)/)[1];
var resultDropdown = $(this).siblings(".result2");
if (jQuery.inArray( "#", res ) < 1) {
resultDropdown.empty();
}else {
$.get("../Admin/Users/SearchUser.php", {userAtd: myString}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
})
}
This sort of works, but jQuery.inArray doesn't accept regex, so it only works when # is clicked, but not for the rest of the letters following. And then it should detect when there is a space after the word so then it knows that the # is done.
When doing console.log(res); The output in log is ["this", "is", "a", "test", "#user"]
What I need is for it to detect when # is clicked and then when that part of the array is finished such as hitting space since hitting space makes the array res now
["this", "is", "a", "test", "#user",""]

You could use the following regex to extract every words that start by "#" and that have space after it in a string.
/#[a-z\d]+/ig
See examples : https://regex101.com/r/WDZNyl/1
Once you get the list, it will be easier for you to find the desired values in database.

I figured out the answer, #Flo's response helped a bit coming up with this. I had to detect two different array lengths and compare the two and find where the # started between both arrays and then set a variable x to the length of the original input and then do a .test as my if statement. Code down below
// #'d feature
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 64) { //Enter keycode
$('.postingArea').on("keyup", function(){
var inputVal = $('.postingArea').val();
var res = inputVal.split(" ");
var res2 = inputVal.match(/#[a-z\d]+/ig);
var resultDropdown = $(this).siblings(".result2");
var x=0;
if(x <= res2.length){
x = res.length-1;
}
if(/#[a-z\d]+/ig.test(res[x])) {
var myString = res[x];
$.get("../Admin/Users/SearchUser.php", {userAtd: myString}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}else {
resultDropdown.empty();
}
})
}
})

Related

How to: $(this) ToUpperCase

I'm no professional and after research, I wasn't able to find a solution.
I have a JavaScript source code for a SharePoint list to implement the InstantListFilter (https://archive.codeplex.com/?p=instantlistfilter) which works!
But I would like to update the source code so that the filter is NOT case sensitive. I was able to replace the the filter word (val) to uppercase (val = val.toUpperCase()). But I have no idea how to get the list-text to uppercase.
$("table.ms-listviewtable").children("tbody").each(function() {
$(this).children("tr").each(function() {
var mismatch = false;
$(this).children("td").each(function(colIndex) {
if (mismatch) return;
if (filterValues[colIndex]) {
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
val = val.toUpperCase(); //my adaption, working for the filter word
$(this).val = $(this).val().toUpperCase(); //not working for the list-text
// verifies the filter word.
if ($(this).is(":not(:contains('" + val + "'))")) {
mismatch = true;
}
}
});
if (mismatch) {
$(this).hide();
} else {
$(this).show();
}
});
});
Does anybody have a solution?
Would be happy with a short reply!
The solution you are trying will also modify the input value to upper case, i'm not sure you want that? Maybe you could assign the input value to a var and see if it contains the text with String.indexOf()
...
val = val.toUpperCase(); //my adaption, working for the filter word
var inputVal = $(this).val().toUpperCase();
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val) === -1) {
mismatch = true;
}
...
thanks for reply!!!
I got it:
var inputVal = $(this).text().toUpperCase();
//alert(inputVal);
// verifies the filter word.
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val.toUpperCase()) === -1) {
mismatch = true;
}

Internal Site Search Jquery against a RegExp

Where am I going wrong? Even one error would help please.
I have an HTML input and a submit button. The idea is to:
Submit search string
Get string value.
Compare string value to regex.
If legit, find instances of the string in the DOM.
Then scroll to the first instance of the matched string as it sits in the DOM.
$("#submit").on("click", function () {
//regex to be compared against
var search = new RegExp();
search = /(^\w[A-z]+)$|(^\d[0-9\.x\.X\.m\.M]+)/;
//grab the string value from the search input
var userin = $("#searchin").val();
var compare = userin.test(search);
if (compare === true) {
var treebody = $('html, body').contents().filter(function (userin) {
if ($('html, body').contents() === userin) {
$('html, body').animate({'scrollTop' : $(treebody).position().top}, 700)
} else {
alert("Please search again or scroll down to find your desired content");
}
});
} else {
alert("Sorry, we couldn't match your search. Please try a region or place or a billboard size e.g. 9x13 ");
}
});
Change the line
var compare = userin.test(search);
it should be
var compare = search.test(userin);
Also check you regular expression. Here is a good reference RegEx.

compare strings at being typed

I'm having some difficulty with a string comparison function. I have a textbox that has a keyup event. when a key is pressed, it calls a function to compare what is in the text box with a list of values. I want to be able to allow the user to type a word in the box and eliminate choices from the list that are not compatible with what has been typed. For instance, if i had this list:
jay
jason
jamie
jamu
jenny
sara
and allowed the user to type:
'j' --> sara should be eleminated as a choice
'ja' --> sara and jenny should be eliminated
'jam' --> only jamie and jamu should be left
'jamu' --> should only leave jamu
the code I have only seems to to it letter by letter and and not cumulatively. Does anyone have any suggestions for a better way to check strings?
thanks
function filterByName(e){
var key = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(key);
fullString=fullString + keychar
..... some other stuff
//iterate over list
var ul = document.getElementById("friendUl");
var liNodes = ul.getElementsByTagName("li");
var nodeLength = liNodes.length
for (i=0;i<=nodeLength-1;i++){
var getFNames= document.getElementsByName('fNames').item(i)
var getLNames = document.getElementsByName('lNames').item(i)
var fullNames = getFNames + " " + getLNames
for (j=0;j<=fullString.length-1;j++){
if(fullString.charAt(j)== fullNames.charAt(j)){
alert(fullNames)
}
}
}
}
'
It seems like you just want to see if the given name starts with the value of fullString.
if (fullName.indexOf(fullString) === 0) {
// It's still valid
} else {
// It's not valid
}
Define a function off of string like this:
String.prototype.startsWith = function(val) {
return 0 == this.indexOf(val);
};
And use that instead of your for loop where you are using charAt(). Specifically, replace this:
for (j=0;j<=fullString.length-1;j++){
if(fullString.charAt(j)== fullNames.charAt(j)){
alert(fullNames)
}
}
With this:
if (fullNames.startsWith(fullString))
alert(fullNames);
when you are doing
fullString=fullString + keychar
you should be doing
fullstring = document.getElementById('TextBoxId').value;
this way, you account for backspaces, etc...

testing user entry on keyup and regex

In my case the requirement is like -
The first name should allow alphabets, some chars like comma, dash and ascent chars.
The code works fine when we try to paste the ascent chars or use "abctajpu" add on in firefox. But as soon as user types in ALT+0192 or any ALT key with num pad.
The keyup function does not work. It lets the user to key in every possible combination with the ALT key.
Here is the sample code..
var namePattern = /^[a-zA-Z,-. \'ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸçÇŠšŽžÅå]$/g;
var negateNamePattern = /[^a-zA-Z,-. \'ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸçÇŠšŽžÅå]/g;
$("#First_Name").bind('keyup paste altKey', function(event) {
var obj = $(this);
if (event.type == 'paste') {
setTimeout(function() {
validateRealTime(event, obj, namePattern, negateNamePattern)
}, 1);
} else {
validateRealTime(event, obj, namePattern, negateNamePattern);
}
});
The key up event will still be fired when they do any ALT key with num pad, however only when they stop typing will the new character be appended.
Is there a specific reason why you need to do a key up event?
You could validate your field whenever they lose focus on the input.
Also, can we see your validateRealTime function?
EDIT
I think I've figured out a way to accomplish what you want.
We'll have to change your function to validate a string passed instead of getting the value of the object:
function validateRealTime(str, regExPattern, negateRegExPattern) {
var fieldVal = str;
fieldVal = fieldVal.replace(/^(\s+)/g,'');
fieldVal = validateInput(fieldVal, regExPattern, negateRegExPattern);
// return the new and validated value
return fieldVal;
}
I've removed the event from the function, but you can add it if you are using it somewhere else.
Also, we need to change from a keyup to a keypress event. This will allow us to determine when the ALT is pressed (ALT + # = one keypress, whereas ALT + # = # keyups)
Futhermore, since the value of the input gets updated on keyup, we need to make sure that on keyup only the validated string appears.
var validatedValue; // Store validate value to display on 'keyup'
var namePattern = /^[a-zA-Z,-. \'ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸçÇŠšŽžÅå]$/g;
var negateNamePattern = /[^a-zA-Z,-. \'ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸçÇŠšŽžÅå]/g;
$("#First_Name").bind('keyup', function(event){
$(this).val(validatedValue);
})
.bind('keypress paste', function(event){
var obj = $(this);
var char;
var string;
var newval;
if (event.type == 'paste'){
setTimeout(function(){validateRealTime(obj.val(), namePattern, negateNamePattern)}, 1);
} else {
// Get the ASCII code of the key pressed and get the Char representation of it
// When we do an ALT+#, it returns only one ASCII value
char = String.fromCharCode(event.keyCode);
// Get the current string and append the character added by the ALT
// We need to do this, because the val() is not updated yet, it still contains
// the old value
string = obj.val() + char;
validatedValue= validateRealTime(string, namePattern, negateNamePattern);
}
});
Also, I have not tested the paste event.
Finally its working....here is the working code...
$("#First_Name").bind('keyup paste', function(event){
var obj = $(this);
if(event.altKey) {
$("#First_Name").bind('keypress', function(event){
setTimeout(function(){validateRealTime(event, obj, namePattern, negateNamePattern)}, 1);
});
} else if (event.type == 'paste'){
setTimeout(function(){validateRealTime(event, obj, namePattern, negateNamePattern)}, 1);
} else {
validateRealTime(event, obj, namePattern, negateNamePattern);
}
});
Thanks a lot for the guidance...the trick was to delay the time so that keyup gets the typed in character.

Improve this search engine detecter with javascript

I have the following code which detects which search engine and what search term has been used:
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help!
Have you tried leveraging existing JS URL parsing schemes? It might save you a bunch of time. For example:
http://blog.stevenlevithan.com/archives/parseuri
It's cutting the "h" off because q= was not in the referrer string. So your start variable is -1. Then you add 2 to that to get your searchTerms var with a substring. You need to check for start to be equal to -1 and return.
I also think your "google" string detection is not bulletproof, I would rather do something like this...
var ref = document.referrer;
var pcol = ref.indexOf("://") + 3;
if(ref.indexOf("google.com") == pcol || ref.indexOf("www.google.com") == pcol) {
// It is google
}
One last thing, you should use decodeURIComponent instead of unescape.

Categories