Adding options to a <select> using jQuery?

后端 未结 30 1644
萌比男神i
萌比男神i 2020-11-22 03:56

What\'s the easiest way to add an option to a dropdown using jQuery?

Will this work?

$(\"#mySelect\").append(\'
相关标签:
30条回答
  • 2020-11-22 04:30

    If someone comes here looking for a way to add options with data properties

    Using attr

    var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
    

    Using data - version added 1.2.3

    var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
    
    0 讨论(0)
  • 2020-11-22 04:31

    You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.

    1. $('#select').append($('<option>', {value:1, text:'One'}));

    2. $('#select').append('<option value="1">One</option>');

    3. var option = new Option(text, value); $('#select').append($(option));

    0 讨论(0)
  • 2020-11-22 04:31

    This is very simple:

    $('#select_id').append('<option value="five" selected="selected">Five</option>');
    

    or

    $('#select_id').append($('<option>', {
                        value: 1,
                        text: 'One'
                    }));
    
    0 讨论(0)
  • 2020-11-22 04:31

    To help performance you should try to only alter the DOM once, even more so if you are adding many options.

    var html = '';
    
    for (var i = 0, len = data.length; i < len; ++i) {
        html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
    }           
    
    $('#select').append(html);
    
    0 讨论(0)
  • 2020-11-22 04:31

    This is the way i did it, with a button to add each select tag.

    $(document).on("click","#button",function() {
       $('#id_table_AddTransactions').append('<option></option>')
    }
    
    0 讨论(0)
  • 2020-11-22 04:33

    Why not simply?

    $('<option/>')
      .val(optionVal)
      .text('some option')
      .appendTo('#mySelect')
    
    0 讨论(0)
提交回复
热议问题