Set the default value in dropdownlist using jQuery

前端 未结 8 1154
盖世英雄少女心
盖世英雄少女心 2020-12-04 23:37

I have many options in my dropdownlist like:


I n

相关标签:
8条回答
  • 2020-12-05 00:14

    val() should handle both cases

      <option value="1">it's me</option>      
    
    
    $('select').val('1'); // selects "it's me"
    
    $('select').val("it's me"); // also selects "it's me"
    
    0 讨论(0)
  • 2020-12-05 00:14
    $('#userZipFiles option').prop('selected', function() {
            return this.defaultSelected;
        });     
    
    0 讨论(0)
  • 2020-12-05 00:15

    if your wanting to use jQuery for this, try the following code.

    $('select option[value="1"]').attr("selected",true);
    

    Updated:

    Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.

    Here below is the updated code.

    $('select option:contains("it\'s me")').prop('selected',true);
    

    You need to use the :contains(text) selector to find via the containing text.

    Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.

    A working example on JSFiddle

    0 讨论(0)
  • 2020-12-05 00:17

    This is working fine:

    $('#country').val($("#country option:contains('It\'s Me')").val());
    
    0 讨论(0)
  • 2020-12-05 00:23

    One line of jQuery does it all!

    $("#myCombobox option[text='it\'s me']").attr("selected","selected"); 
    
    0 讨论(0)
  • 2020-12-05 00:29

    You can just do this:

    $('#myCombobox').val(1)
    
    0 讨论(0)
提交回复
热议问题