1

Here is what I have:

for (i = 0; i < data.length; i++) {
                $("#myDropDownLisTId").find('tbody')  
                .append($('<option>').attr('value', data[i].id).attr('name', data[i].name)
                );               
            }

But the dropdown list always remains the same. Why is this not working? the data variable has beautiful values. Also, I would like before the for loop to empty the dropdown list/ How to do it?

Here is my drop down list in the view:

<%= Html.DropDownList("myDropDownLisTId")%>
6
  • what is data ? is that a json object ? Commented Apr 9, 2012 at 18:08
  • @Shyju Yes, I return return Json(List<TableInDatabase>); Commented Apr 9, 2012 at 18:09
  • @Shyju I added some details. Can you see the question again please? Commented Apr 9, 2012 at 18:11
  • @Shyju But how to empty the dropdown list before that? Commented Apr 9, 2012 at 18:15
  • jQuery is a JavaScript library, not an alternative to JavaScript. "jquery or JS" does not make sense. Commented Apr 9, 2012 at 18:17

4 Answers 4

6

Though the other answers will accomplish what you wish to do, I would recommend writing your option HTML to a string variable and appending it after the loop has finished, rather than appending within the loop. This can have some noticeable performance advantages when your list gets longer. Using .html() will also take care of emptying the list each time.

        var tempList = '';
        for (i = 0; i < data.length; i++) {  
            tempList += '<option value="' + data[i].id + '" name="' + data[i].name +'">' + data[i].text + '</option>';            
        }
        $("#myDropDownLisTId").html(tempList);
Sign up to request clarification or add additional context in comments.

1 Comment

This is a very valid point. Thanks for sharing. I just added this to the accepted answer. +1 for teaching me something today.
2

Try this.

$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

Check my this answer for more details about how to get data from an MVC action to load the dropdown list

EDIT: As per the comment to remove existing data

$("#myDropDownLisTId").empty()
$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

EDIT 2:  Idrumsgood's answer has a very good point. Instead of calling the append method everytime inside the loop, just keep the value inside a variable and call the html method only once.

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

var items=""
$.each(data, function() {
   items+="<option value='" + this.id + "'>" + this.Text + "</option>";
 });
$("#myDropDownLisTId").html(items);

7 Comments

It's working :) But how to empty the dropdown list before that?
replace append with html :)
@FlorianMargaine But now there is only one option tag in the dropdown list
@Shyju And how do I add a separator in the dropdownlist - that can not be selected? "------"
@user1322207: What is a separator ?
|
1

This seems to work: http://jsfiddle.net/ykFJd/2/

JS

var data = [
    {id:'0', name:'test 0'},  
    {id:'1', name:'test 1'},
    {id:'2', name:'test 2'},
    {id:'3', name:'test 3'},
    {id:'4', name:'test 4'},    
];


for (var i = 0; i < data.length; i++) {
    $("#myDropDownLisTId").append(
        $('<option />', {
            'value': data[i].id,
            'name': data[i].name,
            'text': data[i].name
        })
    );               
}​

Comments

0

I wrote a nice function for binding a js hash to a select lists. See my answer at Best way to populate select list with JQuery / Json?

Example usage:

// you can easily pass in response.d from an AJAX call if it's JSON formatted
var users = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Cindy'} ]
setSelectOptions($('#selectList'), users, 'id', 'name');

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.