Adding options to a <select> using jQuery?

后端 未结 30 1670
萌比男神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:18
    $(function () {
         var option = $("<option></option>");
         option.text("Display text");
         option.val("1");
         $("#Select1").append(option);
    });
    

    If you getting data from some object, then just forward that object to function...

    $(function (product) {
         var option = $("<option></option>");
         option.text(product.Name);
         option.val(product.Id);
         $("#Select1").append(option);
    });
    

    Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers

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

    There are two ways. You can use either of these two.

    First:

    $('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
    

    Second:

    $.each(dataCollecton, function(val, text) {            
        options.append($('<option></option>').val(text.route).html(text.route));
    });
    
    0 讨论(0)
  • 2020-11-22 04:21

    If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

    var s= document.getElementById('mySelect');
    s.options[s.options.length]= new Option('My option', '1');
    
    0 讨论(0)
  • 2020-11-22 04:22

    I like to use non jquery approach:

    mySelect.add(new Option('My option', 1));
    
    0 讨论(0)
  • 2020-11-22 04:24
    $('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
    
    0 讨论(0)
  • 2020-11-22 04:25

    We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:

    $("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");
    
    $("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected
    
    $('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected
    

    0 讨论(0)
提交回复
热议问题