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.
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]);
}
for in loop to iterate over an array (without some additional checks in the body of the loop) is incorrect. See this jsFiddle.for..in will not enumerate the native Array properties -- see update jsfiddle.net/BTA7B/3var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
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).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);
});
$("searchKeywords")<-- also, this isn't a valid selector