45

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.

stats101
  • 1,837
  • 9
  • 32
  • 50

3 Answers3

105
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]);
}
Rohit Saini
  • 685
  • 6
  • 13
Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84
  • 1
    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](http://jsfiddle.net/BTA7B/). – Anthony Grist Aug 01 '12 at 11:08
  • 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. – Jitendra Pancholi Aug 01 '12 at 11:16
  • 2
    @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 http://jsfiddle.net/BTA7B/3/ – nbrooks Aug 02 '12 at 13:43
2
var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}
Jayamurugan
  • 1,757
  • 2
  • 14
  • 34
  • 2
    @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). – Anthony Grist Aug 01 '12 at 11:07
0

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);
});
Saeed
  • 473
  • 6
  • 9
  • 1
    Add some explanation along with your answer – Vineeth Sai Nov 12 '18 at 08:56
  • 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](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer - [From Review](https://stackoverflow.com/review/low-quality-posts/21387344) – Nick Nov 12 '18 at 10:31
  • sorry guys, added some explanation – Saeed Nov 12 '18 at 11:03