Hide selected option from another select box - javascript

Edit, yes I am aware of this question but that answer is not completely working for my case
I'm looking for a solution for this case
When a user selects an option from one select box the option should be hidden for the other select boxes.
When a selected option changes or is removed (select a blank option) the previously selected option should become available again to the other select boxes.
The problem with my current code:
When an option changes, the previous option is not "released" to the other select boxes so they can not use it again until the page reloads.
Basically, results in previously selected options are dissapearing from other select boxes.
I included a fiddle so you can see it for youself.
$(document).ready(function() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
var prevValue = $(this).data('previous');
$('.update-select').not(this).find('option[value="' + prevValue + '"]').show();
var value = $(this).val();
if (value) {
$(this).data('previous', value);
console.log($(this).data('previous', value));
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>

It's as simple as this. Just .show() all the option's and reinitialize the select's using your previous code.
$(document).ready(function() {
function intializeSelect() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
};
intializeSelect();
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
$('.update-select').find('option').show();
intializeSelect();
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>

This is my solution:
$(document).ready(function() {
$(document).on('change', '.update-select', function(e) {
$('option').show();
var selectedOptionsGlobal = [];
$.each($('.update-select'), function(key, select) {
var selectedOptionValue = $(select).val();
if (selectedOptionValue !== "") {
selectedOptionsGlobal.push(selectedOptionValue);
}
});
for (var i = 0; i < selectedOptionsGlobal.length; i++) {
$('option[value="'+selectedOptionsGlobal[i]+'"]').hide();
}
});
});

Related

HTML multi select opt group select box always scroll to top

I have implemented HTML opt group select box.
After selecting a top element and scroll down, again when I am selecting an item which is located at the bottom of the select box.scroll position is automatically changing to top.this is not good in terms of usability.I spent lot of times to fix this issue.but still i couldnt.
https://jsfiddle.net/nsandaruwa/tj1f2gyx/5/
$('option').mousedown(function(e) {
e.preventDefault();
var originalScrollTop = $(this).parent().scrollTop();
console.log(originalScrollTop);
$(this).prop('selected', $(this).prop('selected') ? false : true);
var self = this;
$(this).parent().focus();
setTimeout(function() {
$(self).parent().scrollTop(originalScrollTop);
}, 0);
return false;
});
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="" class="form-control select-checkbox" size="5">
<optgroup label="One">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
<optgroup label="Two">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
<optgroup label="Three">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
</select>
Better?
$('option').mousedown(function(e) {
e.preventDefault();
const that = this;
$(this).prop('selected', $(this).prop('selected') ? false : true);
setTimeout(function() { that.scrollIntoView() },10)
return false;
});
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="" class="form-control select-checkbox" size="5">
<optgroup label="One">
<option>Dog 1</option>
<option>Cat 1</option>
<option>Hippo 1</option>
<option>Dinosaur 1</option>
<option>Another Dog 1</option>
</optgroup>
<optgroup label="Two">
<option>Dog 2</option>
<option>Cat 2</option>
<option>Hippo 2</option>
<option>Dinosaur 2</option>
<option>Another Dog 2</option>
</optgroup>
<optgroup label="Three">
<option>Dog 3</option>
<option>Cat 3</option>
<option>Hippo 3</option>
<option>Dinosaur 3</option>
<option>Another Dog 3</option>
</optgroup>
</select>

mark multiple options as selected on page load

I have this multi-select
$('#hide_col').change(function() {
var arr = $(this).val();
localStorage.setItem('hide', arr);
var hide_cols = localStorage.getItem('hide');
var hide;
for (hide = 0; hide <= 28; hide++) {
if (hide_cols.includes('row' + hide)) {
$('.row' + hide).hide();
} else {
$('.row' + hide).show();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group" style="direction: rtl; margin-top: 5px;width: 600px;">
<select name="hide" data-live-search="true" id="hide_col" class="selectpicker w-25 check_info js-example-basic-multiple" multiple data-style="btn-info">
<option value="row1">סטטוס/יום</option>
<option value="row2">תאריך</option>
<option value="row3">שידור/ משחק</option>
<option value="row4">ליגה/סוג שידור</option>
<option value="row5">שידור</option>
<option value="row6">ערוץ</option>
<option value="row7">הערות אישיות</option>
<option value="row8">מיקום</option>
<option value="row9">חדר</option>
<option value="row10">שדר/פרשן</option>
<option value="row11">קווים/פאנל</option>
<option value="row12">עורך</option>
<option value="row13">במאי/עוזר במאי</option>
<option value="row14">מפיק</option>
<option value="row15">טכנאי</option>
<option value="row16">בקליינר/עוזר צלם</option>
<option value="row17">מספר מצלמות/צלמים </option>
<option value="row18">מפקח קול</option>
<option value="row19">REPLAY</option>
<option value="row20">CG</option>
<option value="row21">רשם</option>
<option value="row22">מפיק אופטיוב/טכנאי אופטיוב</option>
<option value="row23">מאפרת/מלבישה</option>
<option value="row24">שיבוץ ציוד</option>
<option value="row25">רכבים/נגררים</option>
<option value="row26">קופה</option>
<option value="row27">כרטיס</option>
<option value="row28">שלח הודעה/מחק שידור</option>
</select>
</div>
how can I trigger the function to select the values from the array after the page is reloading and trigger the hide action as well?
the array is stored in the local store
if I use the $('#hide_col').val('.row'+hide);
inside the function, after the page is loading I get only the last result in the array selected and the hide action is not triggerd
Example cannot run here.. but it should work.
The key change is $('select[name*="hide"] > option[value="row'+hide+'"]').hide();
$( document ).ready(function() {
var arrStr = localStorage.getItem('hide');
hideSelected(arrStr.split(','))
});
$('#hide_col').change(function() {
var arr = $(this).val();
localStorage.setItem('hide', arr);
hideSelected(arr);
});
function hideSelected(arr){
var hide;
for (hide = 0; hide <= 28; hide++) {
if (arr.includes('row' + hide)) {
$('select[name*="hide"] > option[value="row'+hide+'"]').hide();
} else {
$('select[name*="hide"] > option[value="row'+hide+'"]').show();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group" style="direction: rtl; margin-top: 5px;width: 600px;">
<select name="hide" data-live-search="true" id="hide_col" style='height:400px' class="selectpicker w-25 check_info js-example-basic-multiple" multiple data-style="btn-info">
<option value="row1">סטטוס/יום</option>
<option value="row2">תאריך</option>
<option value="row3">שידור/ משחק</option>
<option value="row4">ליגה/סוג שידור</option>
<option value="row5">שידור</option>
<option value="row6">ערוץ</option>
<option value="row7">הערות אישיות</option>
<option value="row8">מיקום</option>
<option value="row9">חדר</option>
<option value="row10">שדר/פרשן</option>
<option value="row11">קווים/פאנל</option>
<option value="row12">עורך</option>
<option value="row13">במאי/עוזר במאי</option>
<option value="row14">מפיק</option>
<option value="row15">טכנאי</option>
<option value="row16">בקליינר/עוזר צלם</option>
<option value="row17">מספר מצלמות/צלמים </option>
<option value="row18">מפקח קול</option>
<option value="row19">REPLAY</option>
<option value="row20">CG</option>
<option value="row21">רשם</option>
<option value="row22">מפיק אופטיוב/טכנאי אופטיוב</option>
<option value="row23">מאפרת/מלבישה</option>
<option value="row24">שיבוץ ציוד</option>
<option value="row25">רכבים/נגררים</option>
<option value="row26">קופה</option>
<option value="row27">כרטיס</option>
<option value="row28">שלח הודעה/מחק שידור</option>
</select>
</div>

How to add and remove <option> with <optgroup> from box A to box B in Safari?

This question is already asked here and it's perfectly answered, but the problem is it doesn't work properly in Safari like it does in Chrome. In Safari, neither optgroup nor option support display: none.
Is there any way to get it to work like it does in Chrome?
Here is codepen Snippet
$.each($('#u-address > optgroup'), function() {
$(this).clone().empty().appendTo('#m-address');
});
myOgVisibility();
//for dblclick
$('#u-address').dblclick(function() {
$.each($('#u-address option:selected'), function() {
var og = $(this).parent().attr('class');
$(this).remove().appendTo('#m-address .' + og);
$(this).removeAttr('selected');
});
myOgVisibility();
});
$('#m-address').dblclick(function() {
$.each($('#m-address option:selected'), function() {
var og = $(this).parent().attr('class');
$(this).remove().appendTo('#u-address .' + og);
$(this).removeAttr('selected');
});
myOgVisibility();
});
function myOgVisibility() {
$.each($('.showUniOgrp > optgroup'), function() {
if ($(this).html().trim() === "") {
//$(this).detach();
//$(this).css({'display': 'none'});
//$(this).attr('disabled', 'disabled').hide();
$(this).css({
'height': '0px !important',
'display': 'none'
});
} else {
//$(this).appendTo('#m-address');
//$(this).css({'display': 'block'});
//$(this).removeAttr('disabled').show();
$(this).css({
'height': 'auto',
'display': 'block'
});
}
});
}
select {
display: inline-block;
width: 30%;
height: 200px;
border-radius: 5px;
overflow: hidden;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="u-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="u-address">
<optgroup class="og-swe" data-opt="qq" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup class="og-ger" data-opt="qq" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</optgroup>
<optgroup class="og-ita" data-opt="qq" label="Italian Cars">
<option value="ferrari">Ferrari</option>
<option value="lamborghini">Lamborghini</option>
</optgroup>
</select>
</div>
<div class="my-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="m-address">
</select>
</div>
You're gonna need a third select with all the optgroups and options which is hidden. You can use it in different ways to achieve what you want but here's one way:
You have all the info in the hidden select (#h-address) and once an option is selected you add a class to it (.slctd) and if unselected you remove the class. Then populate the two visible selects and remove undesired parts from each.
$.each($('#h-address > optgroup'), function() {
$(this).clone().appendTo('#u-address');
});
$('#u-address').dblclick(function() {
$.each($('#u-address option:selected'), function() {
$('#hidden-fields option[value=' + $(this).val() + ']').addClass('slctd');
showFields();
});
});
$('#m-address').dblclick(function() {
$.each($('#m-address option:selected'), function() {
$('#hidden-fields option[value=' + $(this).val() + ']').removeClass('slctd');
showFields();
});
});
function showFields() {
$('#u-address').empty();
$('#m-address').empty();
$.each($('#h-address > optgroup'), function() {
$(this).clone().appendTo('#u-address');
$(this).clone().appendTo('#m-address');
});
$('#u-address option.slctd').remove();
$('#m-address option:not(.slctd)').remove();
$.each($('.showUniOgrp > optgroup'), function() {
if ($(this).html().trim() === "") {
$(this).remove(); //or detach()
}
});
}
select {
display: inline-block;
width: 30%;
height: 200px;
border-radius: 5px;
overflow: hidden;
float: left;
}
#hidden-fields {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="u-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="u-address"></select>
</div>
<div class="my-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="m-address"></select>
</div>
<div id="hidden-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="h-address">
<optgroup class="og-swe" data-opt="qq" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup class="og-ger" data-opt="qq" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</optgroup>
<optgroup class="og-ita" data-opt="qq" label="Italian Cars">
<option value="ferrari">Ferrari</option>
<option value="lamborghini">Lamborghini</option>
</optgroup>
</select>
</div>
Haven't tested on Safari, but it should work.

Enabling/Disabling Select Boxes based on options chosen

I'm trying to enable/disable 2 select boxes based on selections made on a third box (controller) using jQuery.
What I'm trying to achieve is that when the user selects any of the first 2 options on the controller Selection box 2 will enable, when the user selects any of the last 2 options it will disable selection box 2 and enable selection box 3. If the user goes back on their selection this should enable once again selection box 2 and disable selection box 3, however it doesn't.
My code runs perfectly on the first iteration, but if the user comes back both boxes remain disabled no matter what his choice is.
Here's the snippet
$(function() { //document ready
$('#mySelect').change(function() {
if ($('#mySelect :selected').data('type') <= 2 ) { // if user selects the first 2 items
if ( $('#mySelect2 :selected').text() == "Disabled") { //if selection 2 text is Disabled
$('#mySelect2 :selected').text('Select Option'); // replace text with Select Option
$('#mySelect2').removeAttr('disabled'); //remove disabled attribute from select box
};
$('#mySelect').change(function() {
if ( $('#mySelect :selected').data('type') > 2) {
$('#mySelect2').prop('selectedIndex', 0);
$('#mySelect2').attr('disabled', true);
};
});
//$('#mySelect').change(function() { //
// $('#mySelect3').prop('selectedIndex', 0);
// $('#mySelect3').attr('disabled', 'disabled');
// });
}
else if ($('#mySelect :selected').data('type') > 2 ) {
if ( $('#mySelect3 :selected').text() == "Disabled") { // if text on select 3 is "Disabled"
$('#mySelect3 :selected').text('Select Option'); // changes value for text on first option of 3rd box
$('#mySelect3').removeAttr('disabled'); // removes disabled on 3rd checkbox
};
$('#mySelect').change(function() {
if ( $('#mySelect :selected').data('type') <= 2) {
$('#mySelect3').prop('selectedIndex', 0);
$('#mySelect3').attr('disabled', true);
};
});
// $('#mySelect').change(function() {
// $('#mySelect2').prop('selectedIndex', 0);
// $('#myselect3').attr('disabled', 'disabled');
};
});
});
body {
padding: 20px;
background-color: #efefef;
}
div.container {
background-color: #fff;
display:flex;
}
div.result {
margin-top: 20px;
background-color: #ddd;
min-height: 40px;
}
.result > p {
color: red;
}
select {
min-width: 100px;
margin: 20px 10px;
border: 1px solid #074481
}
select option {
line-height: 30px;
color: blue;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<select name="mySelect" id="mySelect">
<option value="0" data-type="0" disabled selected>Please Select Option</option>
<option value="1" data-type="1">option 1</option>
<option value="2" data-type="2">option 2</option>
<option value="3" data-type="3">option 3</option>
<option value="4" data-type="4">option 4</option>
</select>
<select name="mySelect2" id="mySelect2" disabled>
<option value="0" data-type="0" disabled selected>Disabled</option>
<option value="1" data-type="1">option 1</option>
<option value="2" data-type="2">option 2</option>
<option value="3" data-type="3">option 3</option>
<option value="4" data-type="4">option 4</option>
</select>
<select name="mySelect3" id="mySelect3" disabled>
<option value="0" data-type="0" disabled selected>Disabled</option>
<option value="1" data-type="1">Yes</option>
<option value="2" data-type="2">No</option>
</select>
</div>
and here's the fiddle:
https://jsfiddle.net/rodcunha/cu07yfzv/12/
Thank you in advance for your help. I'm sure it is probably something really basic but I'm only starting out JS/jQ development and can't for the life of me figure it out.
There are some issues in your code.
The first is: you cannot attach an event handler each time you enter the same function:
$('#mySelect').change(function() {
Second point is: reduce complexity and make your code more readable. Avoid:
else if ($('#mySelect :selected').data('type') > 2 ) {
Another point is to avoid to repeat lines of code like in:
$('#mySelect3').prop('selectedIndex', 0);
$('#mySelect3').prop('disabled', true);
$('#mySelect3').text('Disabled');
You can chain:
$('#mySelect3').prop({selectedIndex: 0, disabled: true}).find(':selected').text("Disabled");
The snippet:
$(function() { //document ready
$('#mySelect').change(function() {
if ($('#mySelect :selected').data('type') <= 2 ) { // if user selects the first 2 items
if ( $('#mySelect2 :selected').text() == "Disabled") { //if selection 2 text is Disabled
$('#mySelect2 :selected').text('Select Option'); // replace text with Select Option
$('#mySelect2').removeAttr('disabled'); //remove disabled attribute from select box
};
$('#mySelect3').prop({selectedIndex: 0, disabled: true}).find(':selected').text("Disabled");
} else {
if ( $('#mySelect3 :selected').text() == "Disabled") { // if text on select 3 is "Disabled"
$('#mySelect3 :selected').text('Select Option'); // changes value for text on first option of 3rd box
$('#mySelect3').removeAttr('disabled'); // removes disabled on 3rd checkbox
};
$('#mySelect2').prop({selectedIndex: 0, disabled: true}).find(':selected').text("Disabled");
};
});
});
body {
padding: 20px;
background-color: #efefef;
}
div.container {
background-color: #fff;
display:flex;
}
div.result {
margin-top: 20px;
background-color: #ddd;
min-height: 40px;
}
.result > p {
color: red;
}
select {
min-width: 100px;
margin: 20px 10px;
border: 1px solid #074481
}
select option {
line-height: 30px;
color: blue;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<select name="mySelect" id="mySelect">
<option value="0" data-type="0" disabled selected>Please Select Option</option>
<option value="1" data-type="1">option 1</option>
<option value="2" data-type="2">option 2</option>
<option value="3" data-type="3">option 3</option>
<option value="4" data-type="4">option 4</option>
</select>
<select name="mySelect2" id="mySelect2" disabled>
<option value="0" data-type="0" disabled selected>Disabled</option>
<option value="1" data-type="1">option 1</option>
<option value="2" data-type="2">option 2</option>
<option value="3" data-type="3">option 3</option>
<option value="4" data-type="4">option 4</option>
</select>
<select name="mySelect3" id="mySelect3" disabled>
<option value="0" data-type="0" disabled selected>Disabled</option>
<option value="1" data-type="1">Yes</option>
<option value="2" data-type="2">No</option>
</select>
</div>
Try this:
$(function() { //document ready
$('#mySelect').change(function() {
if ($('#mySelect :selected').data('type') <= 2 ) { // if user selects the first 2 items
$('#mySelect2').prop('disabled', false);
$('#mySelect3').prop('disabled', 'disabled');
}
else if($('#mySelect :selected').data('type') > 2 ){
$('#mySelect3').prop('disabled', false);
$('#mySelect2').prop('disabled', 'disabled');
}
else{
$('#mySelect2').prop('disabled', 'disabled');
$('#mySelect3').prop('disabled', 'disabled');
}
});
});
You can add an onChange event for selectors and tie them to their own functions which will make things much easier and cleaner. So it would be something like:
<select onchange='myFunction()'>
<option value="0" data-type="0" disabled selected>Please Select Option</option>
<option value="1" data-type="1">option 1</option>
<option value="2" data-type="2">option 2</option>
<option value="3" data-type="3">option 3</option>
<option value="4" data-type="4">option 4</option>
</select>

Select2 start with input field instead of dropdown

I use the js library select2. This is a screenshot of what I have now:
Start:
Click on dropdown:
Now is it possible to have an input field to start with and not directly a dropdownlist? I know it's possible because you can find it on the select2 site. An example is this:
But the documentation is very brief. This is what I have now:
<input type="text" name="questions[question1]" id="question1" class="question1" style="width:500px"/>
function createQuestionTags(data, question_number){
$(".question" + question_number).select2({
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
data: data,
placeholder: "Enter Question",
allowClear:true
});
}
(The data is received from an ajax call)
What you are seeing is actually a multi-select or multi-value drop down box in that example. It is not a single value drop down box like you are using in your code. Per the Select2 website, select2 will detect that you are trying to use a multi-select box and will automatically apply that styling instead of the default (drop down arrow, etc.).
If you in fact need a single value drop down box, there is no direct way to make it display with the formatting of the multi-select so that it looks like a regular input box. There may be a way to fake it by adding or removing CSS classes. I played around a bit but couldn't find one.
Since you don't want the formatting, the search box, or the multi-select capability (I'm assuming) you probably don't need to use the select2 library.
Update: It looks like you're not the first person to try to do this. They plan to add this feature but it might be a while:
https://github.com/ivaynberg/select2/issues/1345
The only workaround that I could come up with is to use both multiple: true and maximumSelectionSize: 1 when setting up.
Please see my example here: http://jsfiddle.net/DanEtchy/Lnf8j/
This is possible in Select2 4.0.0 with the new selection adapters. You can swap out the SingleSelection with a MultipleSelection (including any relevant decorators) and it should behave as expected.
$.fn.select2.amd.require([
'select2/selection/multiple',
'select2/selection/search',
'select2/dropdown',
'select2/dropdown/attachBody',
'select2/dropdown/closeOnSelect',
'select2/compat/containerCss',
'select2/utils'
], function (MultipleSelection, Search, Dropdown, AttachBody, CloseOnSelect, ContainerCss, Utils) {
var SelectionAdapter = Utils.Decorate(
MultipleSelection,
Search
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
CloseOnSelect
),
AttachBody
);
$('.inline-search').select2({
dropdownAdapter: DropdownAdapter,
selectionAdapter: SelectionAdapter
});
$('.dropdown-search').select2({
selectionAdapter: MultipleSelection
});
$('.autocomplete').select2({
dropdownAdapter: DropdownAdapter,
selectionAdapter: Utils.Decorate(SelectionAdapter, ContainerCss),
containerCssClass: 'select2-autocomplete'
});
});
.select2-selection__choice__remove {
display: none !important;
}
.select2-container--focus .select2-autocomplete .select2-selection__choice {
display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>
<p>With an inline search box</p>
<select style="width: 200px" class="inline-search">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<p>With the search box in the dropdown</p>
<select style="width: 200px" class="dropdown-search">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<p>With the selection hidden when it is focused</p>
<select style="width: 200px" class="autocomplete">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
By default, Select2 will set up the dropdown to have the search (instead of the selection container) which you will need to override if you want to perfectly emulate a multiple select.
Instead of Select2 the better choice would be selectize because Select2 seems dead
The usage is easy:
$('select').selectize(options);
Here is number of examples how to use and customize selectize
In my case, I wanted the user's selections from the dropdown to appear in a list below the dropdown, rather than working like a regular dropdown list. So this workaround worked for me:
$('#myselect').select2({
multiple:true
})
.on('select2:select', function (e) {
//clear the input box after a selection is made
$(this).val([]).trigger('change');
});
Of course that won't work if you want the selected item to stay selected in select2's input box like it does with a regular select2 multiselect list.
Custom implementation using Bootstrap styling, simple but functional:
var elements = $(document).find('select.form-control');
for (var i = 0, l = elements.length; i < l; i++) {
var $select = $(elements[i]), $label = $select.parents('.form-group').find('label');
$select.select2({
allowClear: false,
placeholder: $select.data('placeholder'),
minimumResultsForSearch: 0,
theme: 'bootstrap',
width: '100%' // https://github.com/select2/select2/issues/3278
});
// Trigger focus
$label.on('click', function (e) {
$(this).parents('.form-group').find('select').trigger('focus').select2('focus');
});
// Trigger search
$select.on('keydown', function (e) {
var $select = $(this), $select2 = $select.data('select2'), $container = $select2.$container;
// Unprintable keys
if (typeof e.which === 'undefined' || $.inArray(e.which, [0, 8, 9, 12, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 44, 45, 46, 91, 92, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, 124, 144, 145, 224, 225, 57392, 63289]) >= 0) {
return true;
}
// Already opened
if ($container.hasClass('select2-container--open')) {
return true;
}
$select.select2('open');
// Default search value
var $search = $select2.dropdown.$search || $select2.selection.$search, query = $.inArray(e.which, [13, 40, 108]) < 0 ? String.fromCharCode(e.which) : '';
if (query !== '') {
$search.val(query).trigger('keyup');
}
});
// Format, placeholder
$select.on('select2:open', function (e) {
var $select = $(this), $select2 = $select.data('select2'), $dropdown = $select2.dropdown.$dropdown || $select2.selection.$dropdown, $search = $select2.dropdown.$search || $select2.selection.$search, data = $select.select2('data');
// Above dropdown
if ($dropdown.hasClass('select2-dropdown--above')) {
$dropdown.append($search.parents('.select2-search--dropdown').detach());
}
// Placeholder
$search.attr('placeholder', (data[0].text !== '' ? data[0].text : $select.data('placeholder')));
});
}
/* !important not needed with less */
.form-group {
padding: 25px;
}
.form-group.above {
position: absolute;
bottom: 0; left: 0; right: 0;
}
.select2-container--open .select2-selection {
box-shadow: none!important;
}
.select2-container--open .select2-selection .select2-selection__arrow {
z-index: 9999; /* example */
}
.select2-dropdown {
/* .box-shadow(#form-control-focus-box-shadow); (from select2-boostrap */
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
/* border-color: #input-border-focus; */
border-color: #66afe9;
border-top-width: 1px!important;
border-top-style: solid!important;
/* border-top-left-radius: #input-border-radius; */
border-top-left-radius: 4px!important;
/* border-top-right-radius: #input-border-radius; */
border-top-right-radius: 4px!important;
/* margin-top: -#input-height-base; */
margin-top: -34px!important;
}
.select2-dropdown .select2-search {
padding: 0;
}
.select2-dropdown .select2-search .select2-search__field {
/* !important not needed using less */
border-top: 0!important;
border-left: 0!important;
border-right: 0!important;
border-radius: 0!important;
/* padding: #padding-base-vertical #padding-base-horizontal; */
padding: 6px 12px;
/* height: calc(#input-height-base - 1px); */
height: 33px;
}
.select2-dropdown.select2-dropdown--above {
/* border-bottom: 1px solid #input-border-focus; */
border-bottom: 1px solid #66afe9!important;
/* border-bottom-left-radius: #input-border-radius; */
border-bottom-left-radius: 4px!important;
/* border-bottom-right-radius: #input-border-radius; */
border-bottom-right-radius: 4px!important;
/* margin-top: #input-height-base; */
margin-top: 34px!important;
}
.select2-dropdown.select2-dropdown--above .select2-search .select2-search__field {
/* border-top: 1px solid #input-border; */
border-top: 1px solid #66afe9!important;
border-bottom: 0!important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<link href="https://select2.github.io/select2-bootstrap-theme/css/select2-bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.full.min.js"></script>
<div class="form-group">
<label class="control-label">Below example (click label to focus)</label>
<select class="form-control" id="select2-single-box" name="select2-single-box" data-placeholder="Pick your choice" data-tabindex="1">
<option></option>
<option value="1">First choice</option>
<option value="2">Second choice</option>
<option value="3">Third choice</option>
<option value="4">Fourth choice</option>
<option value="5">Fifth choice</option>
<option value="6">Sixth choice</option>
<option value="7">Seventh choice</option>
<option value="8">Eighth choice</option>
<option value="9">Ninth choice</option>
</select>
</div>
<div class="form-group above">
<label class="control-label">Above example (click label to focus)</label>
<select class="form-control" id="select2-single-box" name="select2-single-box" data-placeholder="Pick your choice" data-tabindex="2">
<option></option>
<option value="1">First choice</option>
<option value="2">Second choice</option>
<option value="3">Third choice</option>
<option value="4">Fourth choice</option>
<option value="5">Fifth choice</option>
<option value="6">Sixth choice</option>
<option value="7">Seventh choice</option>
<option value="8">Eighth choice</option>
<option value="9">Ninth choice</option>
</select>
</div>
Select2's minimumInputLength: 1 option can hide the dropdown on focus/open...
Update: Code cleanup, don't open dropdown on focus.
Use these properties
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
maximumSelectionSize: 1,
});
just call this function on onchange event of dropdown
function ResentForMe(){
var _text=$('.select2-selection__rendered li:first-child').attr('title');
$('.select2-selection__rendered li:first-child').remove();
$('.select2-search__field').val(_text);
$('.select2-search__field').css('width','100%');
}
Note: Remove "Multiple" attribute from select
dudes, add some CSS anywhere:
.select2-dropdown--below {
margin-top: -33px !important;
border-radius: 4px !important;
}
just try it! ;)
Matt,)
this work
$('.search-town-flat').select2({
multiple: true,
placeholder: "Enter values",
allowClear: true,
maximumSelectionLength: 2,
theme : "classic"
}).on('select2:select', function (e) {
$(this).val([]).trigger('change');
$(this).val([e.params.data.id]).trigger("change");
});
I simply formatted a standard input box with CSS to look like a Select2() dropdown:
input {
width: 100%;
padding: 7px 5px;
margin: 1px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
$.fn.select2.amd.require([
'select2/selection/multiple',
'select2/selection/search',
'select2/dropdown',
'select2/dropdown/attachBody',
'select2/dropdown/closeOnSelect',
'select2/compat/containerCss',
'select2/utils'
], function (MultipleSelection, Search, Dropdown, AttachBody, CloseOnSelect, ContainerCss, Utils) {
var SelectionAdapter = Utils.Decorate(
MultipleSelection,
Search
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
CloseOnSelect
),
AttachBody
);
$('.inline-search').select2({
dropdownAdapter: DropdownAdapter,
selectionAdapter: SelectionAdapter
});
$('.dropdown-search').select2({
selectionAdapter: MultipleSelection
});
$('.autocomplete').select2({
dropdownAdapter: DropdownAdapter,
selectionAdapter: Utils.Decorate(SelectionAdapter, ContainerCss),
containerCssClass: 'select2-autocomplete'
});
});
.select2-selection__choice__remove {
display: none !important;
}
.select2-container--focus .select2-autocomplete .select2-selection__choice {
display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>
<p>With an inline search box</p>
<select style="width: 200px" class="inline-search">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<p>With the search box in the dropdown</p>
<select style="width: 200px" class="dropdown-search">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<p>With the selection hidden when it is focused</p>
<select style="width: 200px" class="autocomplete">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>

Categories