1

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...

2
  • 1
    You've set i=3 so you are asking the for loop to skip the first 3 entries Commented May 21, 2021 at 12:25
  • I just realized that, it was from previous testing... Thank you! I feel silly now. Commented May 21, 2021 at 12:30

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

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.