TheExit
TheExit

Reputation: 5320

javascript jQuery - Given a comma delimited list, how to determine if a value exists

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

Answers (5)

Nathan
Nathan

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

Tatu Ulmanen
Tatu Ulmanen

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

SLaks
SLaks

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

John Fisher
John Fisher

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

Dutchie432
Dutchie432

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

Related Questions