Select2 start with input field instead of dropdown - javascript

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>

Related

How to label jQuery mobile select-menu after adding of input-search in sub menu

I am rather new to jquery and ran into the following problem:
I have a main menu and a click on the main menu opens a sub menu with multiple items. Originally, the button that opens the submenu was labeled with the first <option> that has an empty value. And this first <option> (Countries in my case) with empty value was not listed in the submenu. So far so good.
<script src="mbo_master/javascript/jquery-2.1.3.js"></script>
<script src="mbo_master/javascript/jquery.mobile-1.4.5.js"></script>
$(document).on("pagecreate", "#demo-dialog", function (e) {
var form = $("<form><input data-type='search'/></form>"),
page = $(this);
$(".ui-content, this")
.prepend(form);
form.enhanceWithin()
.on("keyup", "input", function () {
var data = $(this).val().toLowerCase();
$("li", page).addClass("ui-screen-hidden")
.filter(function (i, v) {
return $(this).text().toLowerCase().indexOf(data) > -1;
}).removeClass("ui-screen-hidden");
});
$(document).on("pagecontainerhide", function () {
$("#demo-menu li").removeClass("ui-screen-hidden");
$("input", form).val("");
});
});
.ui-selectmenu.ui-popup .ui-input-search {
margin-left: .5em;
margin-right: .5em;
}
.ui-selectmenu.ui-dialog .ui-content {
padding-top: 0;
max-height: 85vh;
overflow-y: scroll;
}
.ui-selectmenu.ui-dialog .ui-selectmenu-list {
margin-top: 0;
}
.ui-selectmenu.ui-popup .ui-selectmenu-list li.ui-first-child .ui-btn {
border-top-width: 1px;
-webkit-border-radius: 0;
border-radius: 0;
}
.ui-selectmenu.ui-dialog .ui-header {
border-bottom-width: 1px;
padding-left: 50px;
}
<label for="demo" id="label">Long list:</label>
<select name="demo" id="demo" multiple="multiple" data-native-menu="false" class="select">
<option data-placeholder="true" value="">Countries</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
After having added a jquery search field on top of the submenu, the first <option> with empty value appears in the submenu, what I don´t want.
I can remove it with
$("#demo option[value='']").remove();
but then the label of the button disappears, too.
data-placeholder="true" didn´t work as well.
I found that the problem is the line
$("#demo-menu li").removeClass("ui-screen-hidden"); in the search-function.
When it is removed, button-labeling and listing of options work as it should, however, the search function doesn´t work properly, of course.
Is there any possibility that allows labeling of the select-button in the main-menu and listing of items with value only in the submenu?
Thanks!
JQM has its own naming convention.
For instance:
the popup which will be created to show a short list of options, will get its own id that is composed by concatenating the "id" of the select followed by the keyword "listbox-popup".
the dialog-page which will be created to show a long list of options exceeding the page height, will get its own id that is composed by concatenating the "id" of the select followed by the keyword "dialog".
So, after thinking about it, I believe the filterable is needed only when a dialog-page will be displayed, as the choice between popup and dialog-page is made dynamically, every time the select is opening.
Therefore the code is even simpler, as the JQM built-in data-filter option can be used here:
HTML:
<div data-role="page" id="page-select-country">
<div data-role="content">
<div class="ui-field-contain">
<label for="country-select">Long list:</label>
<select name="country-select" id="country-select" data-native-menu="false">
<!-- option empty value will be used as data-placeholder -->
<option>Choose Your Country</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
... other oprions...
<option value="WY">Wyoming</option>
</select>
</div>
</div>
</div>
JavaScript:
$(document).on("selectmenucreate", "#country-select", function(e, ui) {
var data = $(this).data("mobile-selectmenu"), hide = {"display": "none"};
data.list
.attr("data-filter", "true")
.find("li[data-placeholder='true']").css(hide);
$(this).on("change", function () {
var cases = {"page": data.menuPageClose, "overlay": data.headerClose},
btnClose = cases[data.menuType];
if ($("option:selected", this).length === 0) {
btnClose
.addClass("ui-icon-delete")
.removeClass("ui-icon-check")
.css("backgroundColor", "initial");
} else {
btnClose
.addClass("ui-icon-check")
.removeClass("ui-icon-delete")
.css("backgroundColor", "#90ee90");
}
});
});
$(document).on("pagecontainerbeforeshow", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.toPage.attr("id") == data["dialogId"]) {
if(!ui.toPage.find(".ui-filterable").length) {
ui.toPage.find(".ui-content").enhanceWithin();
}
}
});
$(document).on("pagecontainershow", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.toPage.attr("id") == data["dialogId"]) {
ui.toPage.find(".ui-filterable input").focus();
}
});
$(document).on("pagecontainerhide", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.prevPage.attr("id") == data["dialogId"]) {
data["list"].find("li").removeClass("ui-screen-hidden");
ui.prevPage.find(".ui-filterable input").val("");
}
});

change color when hovering over option

I made a select with javascript and filled its options with an array. Afterwards I wrote some jquery to try and change the backgroundColor of the option when I hover over it, but nothing seems to work. everytime I hover over the options they are still highlighted blue.
I'm new to javascript and jquery and this is an idea that I had of why this happens: could this be because there is a standard hover function in a select that will always override mine or am I really overlooking a mistake? Because I tested my code before on divs and the code worked like a charm here
My code:
//arraycommObjName is an array with 4 elements to fill my selection
//$('#commObjs') is my select
for (i=0; i < arraycommObjName.length; i++) {
$('#commObjs').append($('<option class="testoptions"></option>').attr("value", arrayCommObjID[i]).text(arraycommObjName[i]));
}
$(".testoptions").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"green":"red")
})
take note yes I know it's better to do this with css but it is asked to me to do it with only javascript and jquery.
You can use select2 and add some CSS to override the default styles.
Below is an example with some horrific colors to prove you can override the default select2 white and blue colors.
$("#states").select2();
#states {
width: 300px;
}
.select2-results__option {
color: orange;
background-color: seashell;
}
.select2-results__option--highlighted {
color: white !important;
background-color: darkgreen !important;
}
.select2-container--default .select2-results__option[aria-selected=true] {
background-color: darkgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="states">
<option value="">Select...</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</select>

Hide selected option from another select box

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();
}
});
});

tidying up jQuery method for validating form

I am validating a form using jQuery.
It is working perfectly, but I just feel the code is quite "bulky". There is a lot of if statements being used to achieve this logic in the app.sendForm.init() function. I think this could be tidied and any advice here would be greatly appreciated. Perhaps I should be using a switch statement instead?
Is there another approach I should take to tidy up this code, or do I just have to accept it is going to be quite longwinded?
I have also posted the question here where more be a more appropriate forum for this type of question.
"use strict";
var app = app || {};
(function(){
app.initialize = {
init: function() {
app.sendForm.init();
}
};
app.sendForm = {
init: function(){
$("#entry").submit(function( event ) {
var userEmail = $("#email"),
userName = $("#first_name"),
userLastName = $("#last_name"),
date = $("#birth_day"),
month = $("#birth_month"),
year = $("#birth_year"),
countryName = $("#country");
app.validation.dateOfBirth(date, month, year);
if(!app.validation.empty(date) ||!app.validation.empty(month) ||!app.validation.empty(year) || !app.validation.empty(countryName) || !app.validation.email(userEmail) || !app.validation.empty(userName) || !app.validation.empty(userLastName)){
event.preventDefault();
alert("didnt send")
if(!app.validation.email(userEmail)) {
userEmail.addClass('invalid');
} else {
userEmail.removeClass('invalid');
}
if(!app.validation.empty(userName)) {
userName.addClass('invalid');
} else {
userName.removeClass('invalid');
}
if(!app.validation.empty(userLastName)) {
userLastName.addClass('invalid');
} else {
userLastName.removeClass('invalid');
}
if(!app.validation.empty(countryName)) {
countryName.addClass('invalid');
} else {
countryName.removeClass('invalid');
}
if(!app.validation.empty(date)) {
date.addClass('invalid');
} else {
date.removeClass('invalid');
}
if(!app.validation.empty(month)) {
month.addClass('invalid');
} else {
month.removeClass('invalid');
}
if(!app.validation.empty(year)) {
year.addClass('invalid');
} else {
year.removeClass('invalid');
}
if(!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
} else {
$('.terms-con').removeClass('invalid');
}
} else {
$("#thank-you").css("display", "block");
alert("sent")
}
});
}
};
/*
* Validation
*/
app.validation = {
email: function(id) {
// Regex, use this to validate the Email. It return true or false.
var emailVal = id.val(),
re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(emailVal);
},
empty: function(id) {
// Use this to validate the Password. Checks if value is empty. It return true or false.
var elementVal = $.trim(id.val());
if(elementVal.length > 0)
return true;
},
dateOfBirth: function(date, month, year) {
var forbiddenAge = 14;
var DOB = date + " " + month + " " + year;
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(age < forbiddenAge){
alert("you are under 14");
}
}
};
app.docOnReady = {
init: function() {
app.initialize.init();
}
};
$(document).ready(app.docOnReady.init);
})(jQuery);
body {
background-color: #fff;
color: #000;
font-family: 'Arial', sans-serif;
margin: 0;
}
#entry {
font-family: 'Arial', sans-serif;
max-width: 400px;
margin: 0 auto;
}
#entry input,
#entry select {
display: block;
margin-bottom: 10px;
}
#entry label {
padding-bottom: 5px;
}
#entry #birth_day,
#entry #birth_month,
#entry #birth_year {
display: inline-block;
}
#entry input[type=submit] {
display: block;
border: 1px solid #1e1e1e;
text-transform: uppercase;
font-family: 'Arial', sans-serif;
font-size: 16px;
font-weight: 400;
text-transform: capitalize;
text-decoration: none;
color: #fff;
line-height: 20px;
letter-spacing: .5px;
max-width: 150px;
height: 40px;
padding: 0 10px;
background: #1e1e1e;
text-shadow: none;
box-shadow: none;
-webkit-box-shadow: none;
font-weight: 400;
margin-top: 15px;
}
#privacy {
font-size: 12px;
}
.invalid {
border-color: #ed0000;
background-color: #ffd8d8;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<!-- JQUERY CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!-- JAVASCRIPT -->
<script src="script.js"></script>
</head>
<body>
<noscript>
For full functionality of this site it is necessary to enable JavaScript.
Here are the <a href="http://www.enable-javascript.com/" target="_blank">
instructions how to enable JavaScript in your web browser</a>.
</noscript>
<div>
<form id="entry">
<label for="first_name">First name:</label>
<input id="first_name" type="text" name="first_name" />
<label for="last_name">Last name:</label>
<input id="last_name" type="text" name="last_name" />
<label>Country/Region</label>
<select id="country" name="country">
<option value="">Select Your Country/Region</option>
<option value="GB">United Kingdom</option>
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
</select>
<label for="email">Email:</label>
<input id="email" type="text" name="email" />
<label>Date of Birth</label>
<select id="birth_day" name="birth_day">
<option value="">DD</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select id="birth_month" name="birth_month">
<option value="">MM</option>
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
<select id="birth_year" name="birth_year">
<option value="">YYYY</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
</select>
<div id="privacy">
<input id="privacy_check" type="checkbox" name="privacy_check" />
<label for="privacy_check">I have read and understood the Terms and Conditions.</label>
</div>
<input type="submit" name="ch_access" value="Submit" />
</form>
</div>
</body>
</html>
You could create a function that performs the if/else statements:
function setInvalidClass(invalidCondition, jQueryObject) {
if(invalidCondition) {
jQueryObject.addClass('invalid');
}
else {
jQueryObject.removeClass('invalid');
}
}
then replace all the if/else statements with a call to the setInvalidClass:
setInvalidClass(!app.validation.email(userEmail), userEmail);
setInvalidClass(!app.validation.empty(userName), userName);
...
You could give a class to the inputs for the type of validation and then just loop through them:
$("#entry").submit(function(event) {
var emptyInputs = $(".empty"), // for empty validation give inputs class of empty
emailInputs = $(".email"), // for email validation give inputs class of email
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
emptyInputs.each(function() {
var input = $(this);
if (!app.validation.empty(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
emailInputs.each(function() {
var input = $(this);
if (!app.validation.email(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});
or alternatively give all inputs that need validating the same class with a data attribute of what type of validation it is:
$("#entry").submit(function(event) {
var inputs = $(".validation"),
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
inputs.each(function() {
var input = $(this),
validationType = input.data('validation-type'),
inputValid;
switch (validationType) {
case 'email':
inputValid = app.validation.email(input);
break;
case 'empty':
inputValid = app.validation.empty(input);
break;
}
if (!inputValid) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) { // this could be added to the loop - just wasn't sure what terms-con element is
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});

change the font size of the selected value after it is being select in select element of html

I want to change the font of selected value in the select tag after the value has been selected .
Following is the code for my html
<select class="form-control" id="session-select">
<option value="SELECT SESSION NUMBER" disabled selected>SELECT SESSION NUMBER</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
Following is the CSS
select{
border:none !important;
box-shadow: none;
font-family: $lgr;
font-size: 35px;
height: 54px;
#media (min-width: $mobile) and (max-width: $mobile-max){
/* Media Query Between Screen 320px and 480px */
font-size: 30px;
}
Not sure you can change the different font-size of option tags, but you can change color and background of selected option like in below demo.
Here is the DEMO http://jsfiddle.net/yeyene/99h7m/1/
Jquery
$('#session-select').on('change', function(){
var val = $(this).val();
$(this).find('option[value='+val+']').css({
'color':'red',
'background':'#e8e8e8'
});
});
I attempted this in the following way and it worked for me:
Html Part:
<select class="form-control" id="session-select">
<option value="SELECT SESSION NUMBER" disabled selected id="selectedDd">SELECT SESSION NUMBER</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
Jquery Part:
<script>
$(document).ready(function () {
$("#session-select").change(function () {
$("#session-select option").removeAttr("id");
var selected = $("#session-select option[value=" + $(this).val() + "]").attr('id','selectedDd');
});
});
</script>
Css Part:
<style type="text/css">
#session-select,#selectedDd {font-size:large!important; }
option:not(#session-select){ font-size:small; }
</style>

Categories