Select2 - Make It Readonly (not Disabled!) From Js
How can I dynamically make a select2 combobox read-only? Here's what I've tried so far: $('...').attr({'readonly': 'readonly'}).trigger('change.select2'); $('...').attr({'readonly'
Solution 1:
This is Solution for Latest select2
(Tested With 4.0.7
) using css only
/*Select2 ReadOnly Start*/
select[readonly].select2-hidden-accessible + .select2-container {
pointer-events: none;
touch-action: none;
}
select[readonly].select2-hidden-accessible + .select2-container.select2-selection {
background: #eee;
box-shadow: none;
}
select[readonly].select2-hidden-accessible + .select2-container.select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container.select2-selection__clear {
display: none;
}
/*Select2 ReadOnly End*/
Solution 2:
See: http://select2.github.io/select2/
I did it with:
$("#modelname-fieldname").select2({disabled:'readonly'});
Where:
modelname-fieldname
is as in:$form -> field($modelname, "fieldname") -> widget(Select2::classname(), [ ... ]);
readonly
is true, false or a stringreadonly
Optionally you can change the cursor when hovering over the select2
field.
Solution 3:
Solution from Select2 - Issue #3387 - Readonly Support:
select[readonly].select2 + .select2-container {
pointer-events: none;
touch-action: none;
.select2-selection {
background: #eee;
box-shadow: none;
}
.select2-selection__arrow,
.select2-selection__clear {
display: none;
}
}
Edit: for versions > 4.07
- as commenters below correctly pointed out:
select[readonly].select2-hidden-accessible + .select2-container {
pointer-events: none;
touch-action: none;
.select2-selection {
background: #eee;
box-shadow: none;
}
.select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container.select2-selection__clear {
display: none;
}
}
Solution 4:
This works for me:
.select2("readonly", true);
.select2("readonly", false);
Solution 5:
The disabled
attribute is not the good way, an HTML Element using this attribute prevents the data sending of the select when form is submit.
For a production mode, I had to find and write a solution... It works with the native readonly
attribute of the select !
Here, applyied to all select into the DOM havin the Select2 mecanism :
$('select[data-select2-id]').on('select2:opening', function (e) {
if( $(this).attr('readonly') == 'readonly') { // Check if select tag is readonly.//console.log( 'readonly, can't be open !' );
e.preventDefault();
$(this).select2('close');
returnfalse;
}
//else{ console.log( 'expandable/selectable' ); }
});
I ve detailled it here wit a complete demo.
Post a Comment for "Select2 - Make It Readonly (not Disabled!) From Js"