0

I'm using this method to add the value and the text to the option, but I need to add also the selected attribute. How can i do this? this is my method...:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
        // is it possible to add here something like this: select: "selected"
    }));
});
Attila Naghi
  • 2,437
  • 5
  • 31
  • 57

2 Answers2

1

You could just build a string and pass it to the append function directly

$.each(items, function(i, item) {
    // do some kind of check here if value matches foo
    var selected = item.value == foo ? 'selected="selected"' : '';

    var opt = '<option value="' + item.value + '" ' + selected + '>';
    opt += item.text + '</option>';

    // append string directly
    $('#mySelect').append(opt);
});
migvill
  • 501
  • 3
  • 6
0

$('select').select2(); // just adding this line of code , it will set your dropdown as default

Attila Naghi
  • 2,437
  • 5
  • 31
  • 57