简体   繁体   中英

How Would I Make Multiple HTML Tags In JQuery Using a For Loop?

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM