0

I want to find any match array in input value:

var vals = new Array('stackoverflow', 'google', 'yahoo');
var val = $('#txtAddress').val();

if ($.inArray(val, vals) != -1) {
  alert('yep');
} else {
  alert('nope');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtAddress" type="text" value="google is better" maxlength="100" id="txtAddress">

but it's not working, I want tp find any match array in value, for example value is google is better and array is google but it won't find google in this value, only works when value is google and array is google like this:

var vals = new Array('stackoverflow', 'google', 'yahoo');
var val = $('#txtAddress').val();

if ($.inArray(val, vals) != -1) {
  alert('yep');
} else {
  alert('nope');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtAddress" type="text" value="google" maxlength="100" id="txtAddress">

so, any solution to find any match array in this value?

Update: I also tried this way but not working too:

var vals = new Array('stackoverflow','google','yahoo');
var val = $('#txtAddress').val();
 
for (var i = 0; i < vals.length; i++) {
    if (vals[i] === val) {
        alert('Value exist');
    } else {
        alert('Value does not exist');
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtAddress" type="text" value="google is better" maxlength="100" id="txtAddress">

And can I alert that matched terms?

Pedram
  • 15,766
  • 10
  • 44
  • 73

2 Answers2

2

You need to check if the values of array present on the input string(substring). For that, you can use indexOf().

If the value is not there, it will return -1

var vals = new Array('stackoverflow', 'google', 'yahoo');
var val = $('#txtAddress').val();
$.each(vals, function(i, a) {
  if (val.indexOf(a) > -1) {
    alert("found in " + a);
  }

});

Fiddle

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

https://api.jquery.com/jQuery.inArray/

$.inArray(val, vals) does not do substring match. it just compares the value the way you are doing in for loop.

I guess you need substring match to find 'google' in 'google is better'

for that i guess you can: How to check whether a string contains a substring in JavaScript?

if val[i].indexOf(vals[i]) > -1 then match else not
Community
  • 1
  • 1
Ritesh
  • 497
  • 4
  • 15