问题
I have an input and I want to know if any of the values in my array exist. For a simple example my array is
var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
I've figured out how to trigger it if I type simply 'sun' for example, but I want to know if 'hhsun' or 'sunee' exist too.
$('input').keyup(function() {
var _val = $(this).val();
$('p').text(_val);
var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
if (_array.indexOf(_val) != -1) {
$('span').text('it worked');
} else {
$('span').text(_array.indexOf(_val));
}
});
fiddle
回答1:
Check to see if an element of _array
is a substring of the textbox's text:
var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
for (var i = 0; i < _array.length; i++) {
if (_val.indexOf(_array[i]) != -1) {
$('span').text('it worked');
return;
}
}
$('span').text('nothing');
Demo: http://jsfiddle.net/WLacb/3/
A slightly more obscure solution would be with regex:
if (/sun|mon|tue|wed|thu|fri|sat/ig.test(_val)) {
$('span').text('it worked');
} else {
$('span').text('nothing');
}
Demo: http://jsfiddle.net/WLacb/9/
回答2:
A simple way to do this is to use the built in jquery.each command to loop through each element of the array and check if it is in the textbox value.
http://jsfiddle.net/WLacb/10/
$('span').text(-1);
$.each(_array, function(key, value) {
if (_val.indexOf(value) != -1) {
$('span').text('it worked');
}
});
来源:https://stackoverflow.com/questions/11965183/if-input-contains-any-word-in-array