stats101
stats101

Reputation: 1877

Split comma-separated input box values into array in jquery, and loop through it

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.

Upvotes: 47

Views: 157647

Answers (3)

Jitendra Pancholi
Jitendra Pancholi

Reputation: 7562

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]);
}

Upvotes: 106

Saeed
Saeed

Reputation: 493

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);
});

Upvotes: 1

Jayamurugan
Jayamurugan

Reputation: 1825

var array = searchTerms.split(",");

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

Upvotes: 3

Related Questions