47

I have a hidden input box from which I'm retrieving the comma-separated text value (e.g. 'apple,banana,jam') using:

var searchTerms = $("#searchKeywords").val();

I want to split the values up into an array, and then loop through the array.

2

3 Answers 3

106
var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

OR

for(var index = 0; index < array.length; index++) {
     console.log(array[index]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Using jQuery to iterate over an array seems like overkill, and using a for in loop to iterate over an array (without some additional checks in the body of the loop) is incorrect. See this jsFiddle.
Thanx for the suggestion, i have removed that part. Above code shall work perfectly fine now. And you can go with simple for loop if you don't want to use jquery.
@anthony It isn't 'incorrect', just not always best practice. Your fiddle doesn't really illustrate the point clearly - the extra alerts are from the mootools library (included by jsFiddle in panel on left) which extends the JS Array prototype. A for..in will not enumerate the native Array properties -- see update jsfiddle.net/BTA7B/3
3
var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

1 Comment

@ChristoferEliasson alert(array[i]) is correct, but the method of iteration isn't. You shouldn't be using a for in loop to iterate over it, otherwise you'll get considerably more alerted than you actually want (such as functions of the Array object).
1

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

3 Comments

Add some explanation along with your answer
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From Review
sorry guys, added some explanation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.