1

I'm trying to create a <select> list with jQuery. Here is what I have:

$('<select />')
    .attr('name', 'location')
    .val("Location 1")
    .appendTo(this);

The value .val("Location 1") does not appear in the drop down list. I'd like to have 3 locations in my list. How do I do this?

Paul Dessert
  • 6,363
  • 8
  • 47
  • 74
  • 1
    You don't add any option in the list. You have to do that creating ` – zerkms Sep 04 '12 at 22:14
  • @zerkms - oh, I see. I misunderstood what .val is doing. I thought it created the option values. – Paul Dessert Sep 04 '12 at 22:16
  • Look at the following link this might help you http://stackoverflow.com/questions/6601952/programmatically-create-select-list – anony Sep 04 '12 at 22:17

3 Answers3

4

Just add <option> elements inside:

$('<select />')
    .attr('name', 'location')
    .append('<option>Location 1</option>',
            '<option>Location 2</option>',
            '<option>Location 3</option>')
    .appendTo(this);

DEMO: http://jsfiddle.net/KUDJ6/

VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Attributes are things such as size, color, etc. If you want to append to a select you will need to append options into the select tag as such:

$('#mySelect').append($('<option>', { value : key }).text(value)); 
Elianora
  • 194
  • 1
  • 13
0

Just create a select element on the page and add the Locations to it..

$(function(){
    var html = '';
    for(var i =1;i<=3;i++){
       html += '<option value="'+ i +'"> Location ' + i + '</option>'; 
    }
    $('#dropdown1').append(html);
});

Check this example http://jsfiddle.net/sushanth009/wMC6j/

Sushanth --
  • 55,259
  • 9
  • 66
  • 105