0

I'm adding the HTML elements in runtime by AJAX call from Javascript file.

I want to use combo-box drop down element to show the list of datas. To acheive this, I'm trying like below in my script file.

    $("#myList").append("<select id=\"mlist\" >");

    for(var i=0;i<datas.length;i++){
        $("#myList").append("<option>"+datas[i]+"</option>");
     }

    $("#myList").append("</select>");

But in the browser, it shows the elements generated as

<select id="mlist"> </select>
 <option>INDIA</option>
 <option>CHINA</option>
  <option>JAPAN</option>

I want the options to be inserted in between to the select element. Anyone kindly suggest me where I'm doing wrong?

2 Answers 2

3

That's not how you do it..You need to find the already appended <select> and then append to it.

var slct =  $("#myList").append("<select id='mlist' />").find('#mlist'); // append the select and find it
for(var i = 0; i < datas.length; i++) {
    slct.append("<option />", { text: datas[i] }); // now append
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good, it's much faster to move the jquery select outside the loop and use a temporary variable (slct).
@CarlJohn glad to have helped :)
If I want to append the same drop down box element in next row, after inserting some label means, shall i still use append method?
0

When you append an element it is closed automatically, so you don't need the second append() to add the closing tag.

Also, you need to append your option elements to the select, not #myList. Try this:

var $select = $("<select />", { id: 'mlist' }).appendTo('#myList');
for (var i = 0; i < datas.length; i++) {
    $select.append($('<option />', { text: datas[i] }));
}

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.