Reputation: 5320
given a list like:
1,3,412,51213,[email protected], blahblah, 123123123123
which lives inside of a input type"text" as a value:
<input type="text" value="1,3,412,51213,[email protected], blahblah, 123123123123, [email protected]" />
How can I determine if a value exists, like 3, or blahblah or [email protected]?
I tried spliting with inputval.split(',') but that only gives me arrays. Is search possible?
Upvotes: 3
Views: 14295
Reputation: 11149
This'll do it:
var val = $('myinput').val()
val = ',' + val.replace(', ',',').replace(' ,',',').trim() + ','; // remove extra spaces and add commas
if (val.indexOf(',' + mySearchVal + ',' > -1) {
// do something here
}
And it makes sure start and end spaces are ignored too (I assume that's what you want).
Upvotes: 0
Reputation: 124778
Utilizing jQuery:
var exists = $.inArray(searchTerm, $('input').val().split(',')) != -1;
exists
is now an boolean value indicating whether searchTerm
was found in the values.
Upvotes: 6
Reputation: 887469
Like this:
if (jQuery.inArray(value, str.replace(/,\s+/g, ',').split(',')) >= 0) {
//Found it!
}
The replace
call removes any spaces after commas.
inArray
returns the index of the match.
Upvotes: 7
Reputation: 22719
var list = inputval.split(',');
var found = false;
for (var i=0; i<list.length; ++i) {
if (list[i] == whateverValue) {
found = true;
break;
}
}
You can be extra picky about the value matching by using "===" if it must be of the same type. Otherwise, just use "==" since it will compare an int to a string in a way that you probably expect.
Upvotes: 1
Reputation: 29160
You'l want to use var arr = theString.split(',')
and then use var pos = arr.indexOf('3');
http://www.tutorialspoint.com/javascript/array_indexof.htm
Upvotes: 0