Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 placeholder showing empty option

too add a placeholder in select2 i have to add an empty option tag in the code like this

<select id="e2" name="rol_id" >
                       <option><option>
                       {foreach from=$data.roles item=rol}
                       <option value={$rol.rol_id}>{$rol.rol_nombre}</option>
                       {/foreach}
 </select>

but when i do that i get this option empty that is selectable enter image description here

how can i not show that option but still the placeholder?

Thanks!

like image 699
Mariana Hernandez Avatar asked Oct 18 '13 14:10

Mariana Hernandez


People also ask

How to show placeholder in Select2?

$('select'). select2({ templateSelection: function (data) { if (data.id === '') { // adjust for custom placeholder values return 'Custom styled placeholder text'; } return data. text; } }); When multiple selections are allowed, the placeholder will be displayed using the placeholder attribute on the search box.

How to add empty option in Select2?

You can set the allowClear option to true . $("#e6"). select2({ allowClear: true, placeholder: "Search for a movie", ... When set to true , the allowClear option causes the Select2 control to display a clear button, but you must also specify the placeholder option for it to work.

How do I stop Select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

How do I delete select 2 options?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();


2 Answers

The empty option is actually for placeholder, I solved it using the code below

var s1 = $('#select2id').select2({
                    multiple: true,
                    placeholder: "Select values"
                });
                s1.val([' ']).trigger("change"); 

the s1.val([' ']).trigger("change"); did the trick

like image 177
Jervie Vitriolo Avatar answered Sep 20 '22 13:09

Jervie Vitriolo


It's a late answer, but it can help someone.

I have modal with a select2 input.

We need to add <option></option> for the placeholder to be shown.

HTML

<select  id="Name">
  <option></option>
  <option value="John">John</option>
  <option value="Brian">Brian</option> 
  <option value="Carl">Carl</option>
</select>

If I want the placeholder to appear.

Jquery

$('#Name').select2({placeholder: 'Select a Name'});

$('#Name').select2('val', '');

If I want to see a value on the select2 input:

$('#Name').select2('val', 'John');
like image 32
devwebapp Avatar answered Sep 17 '22 13:09

devwebapp