1

I am trying to fetch data from array in a datalist using Jquery, but its not working. I am getting the data in array correctly. I have tried forEach loop, for loop and even while loop. for for and while loop, i got the error

Uncaught SyntaxError: Unexpected token 'while'/'for'

in $.each loop, i get the result in one line with comma separated.

Here is my code of fetching and displaying data in array

var salesman_datalist = [];
for(var i = 0; i<=10; i++){
    if(data['salesman'][i]){
        salesman_datalist[i] = data['salesman'][i];
    }
}
console.log(salesman_datalist);

Here is code for while loop

j = 0;
cols += '<td class="col-sm-2"><input list="salesmanlist"><datalist id="salesmanlist">'+while(j <= salesman_datalist.length){ + '<option value="01">'+val+'</option></br>'+ j=j+1 } + '</datalist></td>';

for for loop using its correct syntax Here is the code of foreach loop

cols += '<td class="col-sm-2"><input list="salesmanlist"><datalist id="salesmanlist">'+$.each(salesman_datalist,function(val){ + '<option value="01">'+val+'</option></br>' }) + '</datalist></td>';

but here i received its result:

<datalist id="salesmanlist">usama,0.02,ali,0.01,Ali,,Usama Shakeel,,Haider,0.22</datalist>
2
  • while is a statement, not an expression. You can't use it as a subexpression. Commented Jul 31, 2021 at 7:19
  • @Barmar: so what can be the possible solution or syntax? Commented Jul 31, 2021 at 7:21

1 Answer 1

1

Use .map() to iterate over an array, and .join() to concatenate the results into a single string.

cols += '<td class="col-sm-2"><input list="salesmanlist"><datalist id="salesmanlist">'+
    salesman_datalist.map(val => '<option value="01">'+val+'</option>').join('<br>') + 
    '</datalist></td>';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.