Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 938
stats101 Avatar asked Aug 01 '12 10:08

stats101


People also ask

How do you split comma separated values in an array?

split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How Split Comma Separated Values in jquery?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc.

How do you split a string after a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);


2 Answers

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]); } 
like image 117
Jitendra Pancholi Avatar answered Sep 16 '22 14:09

Jitendra Pancholi


var array = searchTerms.split(",");  for (var i in array){      alert(array[i]); } 
like image 44
Jayamurugan Avatar answered Sep 20 '22 14:09

Jayamurugan