简体   繁体   中英

How to pre select value with “Select2”

I have read some post, but i can't get this to work! I'm trying to pre-select "2015" in "Select2", but nothing is selected!

As, a bonus i'd like help with switching the static dates, to "thisYear" and "pastYear". How should that JS look like together?

HTML

<!-- Select2 choose_year -->
<div>
  <input type='hidden' class='col-md-2' id='choose_year' name='choose_year'>
</div>

JS

$(document).ready(function() {
  $("#choose_year").select2({
    data:[
      {id:0,text:'2015'},
      {id:1,text:'2014'}
    ],
    val: ["0"]
  });
});

Try the val() method

$("#choose_year").select2({
    data: [{
        id: 0,
        text: '2015'
    }, {
        id: 1,
        text: '2014'
    }],
    val: ["0"]
}).select2('val', 1);

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM