Reputation: 37
I am trying to make a dynamic option list using JQuery, though when I run the code, only one option tag out of n option tags (n being any real positive integer). Here is an example array:
My Code:
$.getJSON('http://localhost:3006/search', function(data){
alert(data.names.length);
var i;
var arrLen = data.names.length; //In this case, the names array up top
for(i = 3; i < arrLen; i++){
$('#name').append($('<option></option>').text(data.names[i][0]).val(data.names[i][0]));
}
});
I keep getting the very last option tag in the array, but nothing else...
Upvotes: 1
Views: 422
Reputation: 47
This is my code. May it will help you
HTML PART:-
<select id="main"></select>
JS PART:-
$(document).ready(function(){
let main = $("#main");
let optionText = ['Option1','Option2','Option3'];
optionText.forEach(index => {
let html = `<option>${index}</option>`;
main.append(html);
});
});
Upvotes: 0
Reputation: 337637
There's a few issues here. Firstly the main problem is that you set i = 3
in your loop, so you start from the 4th element of the array, not the first.
Secondly the correct jQuery method is val()
, not value()
, and you need to chain that call with text()
on the first append()
, not create two separate option
elements. Try this:
let data = {
names: ['John Doe', 'Jane Doe', 'Stephan Doe', 'Emily Doe']
}
// in your AJAX callback:
for (var i = 0; i < data.names.length; i++) {
$('#name').append($('<option></option>').text(data.names[i]).val(data.names[i]));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>
As an aside note that you can improve performance of the code by using map()
to create an array of HTML strings to append to the DOM once instead of creating a brand new jQuery object which gets appended to the DOM in each iteration of the loop:
let data = {
names: ['John Doe', 'Jane Doe', 'Stephan Doe', 'Emily Doe']
}
// in your AJAX callback:
let options = data.names.map(n => `<option value="${n}">${n}</option>`);
$('#name').append(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>
Upvotes: 2