1

I have written a jQuery to generate a dynamic drop-down list. How can I set the default text in it(Ex: Select a city)? Thanks!

Here is the script:

var ss = $('#ss');
var select = $('<select></select>').attr({ id: name, name: name });

$.each(u.Options, function (i, option) {
   select.append($('<option</option>').val(option.Value).text(option.Text));
})
ss.append(select);
Roman Melnyk
  • 1,097
  • 1
  • 8
  • 21
Isuru
  • 950
  • 1
  • 13
  • 34

2 Answers2

4

You can create a first option before the $.each loop to set the default choice:

var $ss = $('#ss');
var $select = $('<select />', { id: name, name: name });    
$('<option />', { text: 'Select a city', value: '' }).appendTo($select);

$.each(u.Options, function (i, option) {
    $('<option />', { text: option.Text, value: option.Value }).appendTo($select);
})
$ss.append($select);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Just prepend an option somewhere ?

select.prepend('<option>Select a city</option>');

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388