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...
Related
To summarize, for my program, I want to be able to detect the 't', and prevent the user from adding something with a quantity of '3t', '3t3', or anything of that matter.
In other words, if the quantity starts with a number, but has letters in it, it will still go through and be added, which is what I DON'T WANT.
Here's the code for where I add things. Is there any approach I should do differently?
function addProduct(){
var input = document.getElementById("productName").value;
var input2 = document.getElementById("cost").value;
var input3 = parseInt(document.getElementById("quantity").value);
var s_input3 = input3.toString();
var table = document.getElementsByTagName('table')[0];
if (isNaN(input2) || input2<0)
{
alert("not a number");
return(-1);
}
if (isNaN(input3) || input3<0)
{
alert("not a number");
return(-1);
}
// MY ATTEMPT OF DETECTING THE 't'
for (i = 0; i < s_input3.length; i++)
{
console.log(s_input3.length)
if(!(isNaN(s_input3[0]) && isNan(s_input3[i])))
{
alert("not a number")
return(-3)
}
}
You don't have to go through each of the character in the string. You can just do isNaN() on the input value.
The isNan() function does work on 3t as this code example shows. It might seem initially counter intuitive as a double negative, but the global function tests 'is not a number' so a number is false and a string true. Try code example below.
<html>
<body>
<p id="testOutput"></p>
<button onclick="testNumber()">Test is number</button>
<script>
function testNumber() {
var output = "";
output= output + isNaN('3t') + ": 3t<br>";
output = output + isNaN(3) + ": 3<br>";
document.getElementById("testOutput").innerHTML = output;
}
</script>
</body>
</html>
Output is:
true: 3t
false: 3
W3Schools Ref
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();
}
})
}
})
I am currently building a filter based on div class's and contents.
I was wondering if it is possible to pass a string like follows into a function:
"£0.01 - £100.01"
and then have the function show all div's where the html of that div is between this range
so say I have a div with a class of "price" and its contents were: £10.30
from running this function and passing the string of "£0.01 - £100.01" into it it would hide all div's similar to how I have done it in the js below then only show the div's where the div class "price"'s contents were within the selected price range.
I have managed to do something similar with a brand filter which I will provide here:
function brand(string){
var brand = string;
$('.section-link').hide();
$('.section-link').children('.brand.' + brand).parent().show();
if (brand == "All Brands"){
$('.section-link').show();
}
}
Any general advice or code is greatly appreciated to help achieve this :)
Thanks,
Simon
Edit:
Target div example:
<div class="section-link">
<div class="price"> £56.99</div>
</div>
Reply's are helping a lot, the filter function looks awesome so thanks for pointing that out.
I am just trying to find a way to split the initial string being past in, into two values one low and one high as well as stripping the £ signs
Edit:
managed to split the original string:
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
alert(rangearray[0]);
alert(rangearray[1]);
FINAL EDIT:
From the reply's I have kind of been able to make a function, however it is not entirely working :) can anyone spot what I have done wrong?
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0];
high = rangearray[1];
$('.section-link').children('.price').each(function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
if (low <= divprice && high >= divprice){
$(this).parent().show();
}
})
}
Okay its working, I had spaces in my string. The final function (although messy :P) is:
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0].toString();
high = rangearray[1].toString();
lowmain = low.replace(/ /g,'');
highmain = high.replace(/ /g,'');
$('.section-link').children('.price').each(
function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
var maindivprice = divprice.replace(/ /g,'');
if (lowmain <= maindivprice && highmain >= divprice){
$(this).parent().show();
}
})
}
I'd use a function like this one, where range is the string you gave
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
$(".price").parent().hide();
Then, you can filter all the items with in-range prices and show them:
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
Use jQuery's filter()
An example -> http://jsfiddle.net/H6mtY/1/
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
I would go by something like:
Get all the divs that have prices.
Iterate through all:
Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
If they are just go to the next (use continue maybe)
Else (not in the range) add a class like .hide so it can be blended through css (or just use the blend function from jquery)
I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long.
What I'd like to do is the following:
when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character.
So when someone types 44444444444 then in the textbox appears 44 44 444 4444.
I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
Is any solution to do that?
You could do something like this:
http://jsfiddle.net/ffwAA/4/
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});
Have you tried the maskedInput plugin?
http://digitalbush.com/projects/masked-input-plugin/
I think it can solve your problem.
Hope this helps. Cheers
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.