Answer the question
In order to leave comments, you need to log in
Why is the variable outside of the keyup event handler checked once?
There is a form for entering a link. We check in real time that the user started to write a link from http:// or https://. I set hyper = RegExp to the variable and substituted it into the condition via test(), which is located in the keyup handler function.
For clarity, an individual element will change color to green if true and to red if false.
The question is.
If the variable is declared inside the handler function, then everything is fine. Those. when we entered http:// , then the next block is always green, but I need a global variable, because you need to substitute the same variable in another handler and somehow it will not be beautiful if you multiply it.
And the global one starts "blinking" when we enter http:// and continue typing. Explain this behavior and advise how to turn it around so that it works normally with a global variable.
View here: Click me
<div class="card-body">
<form action="">
<input tyle='text' id='long-link' name="link">
</form>
</div>
var long = $('#long-link'), hyper = new RegExp ('^https://|^http://','g');
long.keyup(function(){
if (hyper.test(long.val())) {
$('.card-body').css({'background':'#4cfa76'});
}
else $('.card-body').css({'background':'#af1d1d'});
});
Answer the question
In order to leave comments, you need to log in
Explain this behavior
g
- that is, all matches are searched for the pattern, not just the first one. You call the test method - a match is found, cool. You call again - the search does not start from the beginning, but from the place where it ended last time. Of course, nothing was found this time. You call test a third time - everything is fine again, because the last time there were no matches, the search is again performed from the beginning of the string.please advise how to turn it out so that it works normally
g
. hyper.lastIndex = 0;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question