How to set selected value on select using selectpicker plugin from bootstrap

前端 未结 18 2241
日久生厌
日久生厌 2020-11-27 13:29

I\'m using the Bootstrap-Select plugin like this:

HTML:


                        
    
提交评论

  • 2020-11-27 13:52

    The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:

    //Get the text using the value of select
    var text = $("select[name=selValue] option[value='1']").text();
    //We need to show the text inside the span that the plugin show
    $('.bootstrap-select .filter-option').text(text);
    //Check the selected attribute for the real select
    $('select[name=selValue]').val(1);
    

    Edit:

    Like @blushrt points out, a better solution is:

    $('select[name=selValue]').val(1);
    $('.selectpicker').selectpicker('refresh')
    

    Edit 2:

    To select multiple values, pass the values as an array.

    0 讨论(0)
  • 2020-11-27 13:53
    var bar= $(#foo).find("option:selected").val();
    
    0 讨论(0)
  • 2020-11-27 13:53

    User ID For element, then

    document.getElementById('selValue').value=Your Value;
    $('#selValue').selectpicker('refresh');
    
    0 讨论(0)
  • 2020-11-27 13:54
    $('.selectpicker option:selected').val();
    

    Just put option:selected to get value, because the bootstrap selectpicker change to and appear in diferent way. But select still there selected

    0 讨论(0)
  • 2020-11-27 13:59
    $('select[name=selValue]').val(1);
    $('.selectpicker').selectpicker('refresh');
    

    This is all you need to do. No need to change the generated html of selectpicker directly, just change the hidden select field, and then call the selectpicker('refresh').

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