Reputation: 22509
I have an input html element and I am using a blur funtion in jquery to check if the value contains an specific element but my code is not working.
jQuery( "#email" ).blur(function() {
...
var arr = ["1","6","7"];
if(this.value()){ // check if the string value contains characters in arr Array
..
any idea?
I tried also to use indexOf()
but still not working
} ...
...
Upvotes: 2
Views: 43
Reputation: 19
I have a different approach, I hope will be of great help:
(function($) {
var arr = ["1","6","7"];
$(document).ready(function() {
var email = document.getElementById("email");
var lastCharacter;
email.addEventListener("input", function(e) {
lastCharacter = this.value.substr(-1);
for (var i = 0; i < arr.length; i++) {
if (arr[i] === lastCharacter) {
console.log("Exist - Contains an specific element of the Arr");
}
}
}, false);
});
})(jQuery);
Upvotes: 0
Reputation: 50326
Hope this snippet will be useful
// Defining array of predefined chars outside the blur event.
// No need to define it on every blur event.
var arr = ["1","6","7"]; //array of predefined chars.
$( "#email" ).blur(function(event) { // Expecting an input element
var _getText = $(this).val(); // get the value from input
for(var i = 0;i<arr.length;i++){ // loop through array of predefined chars
// use indexOf to check if input val
//contain any of predefined chars
if(_getText.indexOf(arr[i]) ==-1){
console.log(arr[i] + " is not present in the string");
}
else{
console.log(arr[i]+ " is present in the string");
}
}
})
Upvotes: 0
Reputation: 938
You can use a combination of some and indexOf
jQuery("#email").blur(function() {
var arr = ["1","6","7"];
// Check if string contains characters above
var charactersInString = arr.some(function(chr) {
return this.value.indexOf(chr) >= 0;
});
// charactersInString will be true if any of the
//characters in the array are in the input string
});
Upvotes: 2