简体   繁体   中英

select2 should have placeholder and allow deselection

I am using the select2 below which is built dynamically using PHP and is used as a filter. I need to allow the users to unselect their choice.

$this->data['years'] = range(1, 5);

<select class="select2" id="dpyr" name="dpyr">
    <option></option>
     <?php foreach ($years as $year) : ?>
           <option value="<?=$year; ?>"><?=$year?></option>
     <?php endforeach; ?>
</select>

I am trying to add the placeholder using jquery but it just doesn't work. I'm out of ideas and have tried altering this many times.

<script>
$(document).ready(function() {
    $("#dpyr").select2({
            placeholder: "Select a year",
            allowClear: true
        });
    });
    $( "#dpyr" ).val('').trigger('change');
}
</script>

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