select2 | jQuery based replacement for select boxes | Plugin library
kandi X-RAY | select2 Summary
Support
Quality
Security
License
Reuse
- The mousewheel event handler
- Normalizes a name to be replaced .
- Calculate scroll bar width
- Create a require function that calls the module .
- Returns the fallback message for an action .
- call this module
- An ending - like function .
- Helper function to adjust the size of the old event
- Split name into namespace .
- Adjust the next scroll bar to account for scrollbar
select2 Key Features
select2 Examples and Code Snippets
Trending Discussions on select2
Trending Discussions on select2
QUESTION
I want to hide option from previous selected dropdown but my solution only works for two dropdown list.
This means that when I come to third dropdown list it will not display selected option from second dropdown list which is ok but it will display selected option from first one.
So, as I understand, methods I'm using overrides the last one that's why it not works.
Here is my select lists:
And my script: strong text
function getSelectValue(select1) {
$("#select2 option[value='" + select1 + "']").hide();
$("#select2 option[value!='" + select1 + "']").show();
$("#select3 option[value='" + select1 + "']").hide();
$("#select3 option[value!='" + select1 + "']").show();
}
function getSelectValue2(select2) {
$("#select1 option[value='" + select2 + "']").hide();
$("#select1 option[value!='" + select2 + "']").show();
$("#select3 option[value='" + select2 + "']").hide();
$("#select3 option[value!='" + select2 + "']").show();
}
function getSelectValue3(select3) {
$("#select1 option[value='" + select3 + "']").hide();
$("#select1 option[value!='" + select3 + "']").show();
$("#select2 option[value='" + select3 + "']").hide();
$("#select2 option[value!='" + select3 + "']").show();
}
ANSWER
Answered 2022-Apr-16 at 18:45I created a single function that handles unhiding and hiding of all options, then filters the other dropdowns' options based on all selected values. Here's the function/demo:
function hideOthers() {
// Get all selected values
let selectedValues = $(".form-control option:selected").map(function() {
if (this.value.length === 0) {
return null;
}
return this.value;
});
// Unhide all so we can hide the correct ones
$("select.form-control option").removeAttr('hidden');
// Filter out the selected values from dropdowns
$(".form-control").each(function() {
var selectElem = $(this);
$.each(selectedValues, function(index, value) {
// If the selected value from the array is from the applicable , skip hiding
if (selectElem.find("option:selected").val() !== value) {
selectElem.find(`option[value="${value}"]`).attr('hidden', true);
}
});
});
}
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
QUESTION
On client side (there is no server side) we have html file with javascript which we are open in browser. In HTML file we include bootstrap and select2 plugins to create UI interface and we include one file with data which have more than 10 000 rows. This is part of basic.html file:
....
...
This is part of mydata.js file:
var mydata = [{id: 0, text: "aa"}, ..... ...... {id: 10000, text: "aa 10000"}];
Question: Because variable mydata is very big, we have bad responsive time when we are selecting data. How can we restrict Select2 plugin to initially select only 10 rows on begining (initially when we load the script) and every time when trying to find some data? On the other words, results for showing must be limited.
There are no server side, no ajax, no (my)sql server, no any other programing language, only html, javascript and bootstrap5 with select2 plugin.
ANSWER
Answered 2022-Mar-04 at 12:52If the problem come from the generation of the select by select2, i don't really see a solution. for me, you can replace select2 element by a autocomplete input text w3school (I tested it with some autogenerated data, 200 000 object to be exact, wit hsame structure as you and it's not too bad)
QUESTION
I am populating Select2 with AJAX data. My code is like below.
function formatState(state) {
if (!state.id) { return state.text; }
var output = $(''); // I would like get data `text[1]` of `processResults` here.
return output;
};
//more code here
cellEle.html(``);
let selectEle = cellEle.children("select").select2({
//more code here
ajax: {
//more code here
processResults: function (data) {
var options = [];
if (data) {
$.each(data, function (index, text) {
options.push({ id: index, text: text[0]});
});
}
return {
results: options,
more: false
};
},
},
templateSelection: formatState,
});
I would like get AJAX data text[1]
of processResults
inside formatState()
of templateSelection
.
How can I get it ?
ANSWER
Answered 2022-Jan-20 at 18:03You can pass any extra data via processResults
. In your case it can be
var options = [];
if (data) {
$.each(data.items, function (index, text) {
options.push({ id: index, text: text[0], text2: text[1] /* <-- extra data */});
});
}
return {
results: options,
more: false
};
Then access it in templateSelection
if (!state.id) {
return state.text;
}
return $(`${state.text} & ${state.text2}`);
QUESTION
Getting below error after installed latest node.js (v16.13.1)
Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93) For more information on which environments are supported please see: https://github.com/sass/node-sass/releases/tag/v4.14.1 I have created static pages for my application and use sass and gulp
I have a static pages and using Sass in the page and use gulp to run on the browser.(npm install). Below are the version which worked my application:
- Node.js - 12.18.0
- gulp - "4.0.2"
- "gulp-sass": "4.1.0"
Package.json file
"scripts": {
"start": "gulp watch"
},
"dependencies": {
"@fortawesome/fontawesome-free": "5.15.1",
"@ttskch/select2-bootstrap4-theme": "^1.5.2",
"bootstrap": "4.5.3",
"bootstrap-datepicker": "^1.9.0",
"jquery": "3.5.1",
"jquery.easing": "^1.4.1",
"select2": "^4.1.0-rc.0",
"gulp": "4.0.2"
},
"devDependencies": {
"browser-sync": "2.26.13",
"del": "6.0.0",
"gulp": "4.0.2",
"gulp-autoprefixer": "7.0.1",
"gulp-clean-css": "4.3.0",
"gulp-header": "2.0.9",
"gulp-plumber": "^1.2.1",
"gulp-rename": "2.0.0",
"gulp-sass": "4.1.0",
"gulp-uglify": "3.0.2",
"merge-stream": "2.0.0"
}
Even using command npm rebuild node-sass
is not changing anything.
ANSWER
Answered 2022-Jan-12 at 23:22gulp-sass 4.1.0 uses node-sass 4, and node-sass 4 does not support Node.js 16, as indicated in this table.
To support Node.js 16, upgrade gulp-sass: the latest version today is 5.1.0:
npm install -D gulp-sass@5.1.0
This will give you node-sass 7, which supports all current versions of Node.js, including Node.js 16.
QUESTION
I am trying to add defer and async to my script tags to increase it is performance
here is the code that I am using
function add_defer_attribute($tag, $handle) {
print('hi');
echo('hi');
// add script handles to the array below
$scripts_to_defer = array('jquery-core-js','fortuna.lib-js');
foreach($scripts_to_defer as $defer_script) {
if ($defer_script === $handle) {
return str_replace(' src', ' defer="defer" src', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);
function add_async_attribute($tag, $handle) {
print('hello');
echo('hello');
// add script handles to the array below
$scripts_to_async = array('jquery-core-js', 'fortuna.lib-js');
foreach($scripts_to_async as $async_script) {
if ($async_script === $handle) {
return str_replace(' src', ' async="async" src', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);
I added this code at the bottom of function.php that is found in the theme that I am using
but it does not work, I have added the id of the scripts that I need to defer and async
nothing happen, can anyone advise what should I do
here are the script tags on my site
ANSWER
Answered 2022-Jan-12 at 19:21Replace
$scripts_to_defer = array('jquery-core-js','fortuna.lib-js');
With this
$scripts_to_defer = array( 'jquery-core', 'fortuna.lib' );
You don't need to add -js
to handle because WordPress automatically adds when enqueue scripts Try the below code.
function add_defer_attribute( $tag, $handle ) {
// add script handles to the array below
$scripts_to_defer = array( 'jquery-core','fortuna.lib' );
foreach( $scripts_to_defer as $defer_script ) {
if ($defer_script === $handle) {
return str_replace( ' src', ' defer="defer" src', $tag );
}
}
return $tag;
}
add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );
function add_async_attribute( $tag, $handle ) {
// add script handles to the array below
$scripts_to_async = array( 'jquery-core', 'fortuna.lib' );
foreach( $scripts_to_async as $async_script ) {
if ($async_script === $handle) {
return str_replace( ' src', ' async="async" src', $tag );
}
}
return $tag;
}
add_filter( 'script_loader_tag', 'add_async_attribute', 10, 2 );
QUESTION
I am trying to populate some preselected values to Select2. My code is like below.
(function($) {
$(document).ready(function() {
$(".volunteer").on("click", function (event) {
let element_id = event.target.id;
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
// Populate select element
cellEle.html(``);
// Initialise select2
let selectEle = cellEle.children("select").select2({
allowClear: true,
maximumSelectionLength: 3,
ajax: {
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
dataType: 'json',
data: function (params) {
return {
action: 'get_data',
};
},
type: "post",
processResults: function (data) {
var options = [];
if ( data ) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
return {
results: options
};
}
}
});
selectEle.select2('open');
$.ajax({
type: "POST",
dataType: 'json',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
success: function (data) {
var options = [];
if (data) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
selectEle.val(options).trigger('change'); // I am trying to attach value here. But it is not working.
}
});
selectEle.on('select2:select', function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
element_id: element_id,
action: 'save_data'
}
});
});
selectEle.on("select2:unselecting", function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
task_id: element_id,
action: 'save_data'
}
});
}).trigger('change');
}
});
});
})(jQuery)
I am trying to attach values but it is not working.
I am trying to something like this.
ANSWER
Answered 2022-Jan-04 at 21:01The options should be appended to the select element rather than selected with .val()
. Details on this can be found in the documetation here.
An updated snippet of the code to .append
the preselected values:
$.ajax({
type: "POST",
dataType: "json",
url: "url",
data: {
element_id: element_id,
action: "get_preselect_values",
},
success: function (data) {
if (data) {
$.each( data, function( index, text ) {
// Declare a new Option for the value - Note id is set to text
const option = new Option(text, text, true, true);
// Append the value to the select element
selectEle.append(option).trigger('change');
});
}
}
});
Please note the id
of the preselected values must match the id
of the retrieved list of values. The id
in the question is the index of the item in the array, whcih won't match the preselected index. If these values don't match you'll be able to select preselected items twice.
To ensure the values match you could update your code to set the id
to the same string as the text
. This would need to be done when adding values options.push({ id: text, text: text });
. It must also be done when preselecting values as per the example above new Option(text, text, true, true);
where text
is passed as both the text and value of the Option.
Additionally you may wish to load the already selected values before initailising select2, otherwise the values may appear after select2 has opened which could cause unexpected behaviour.
QUESTION
I have configured my select via select2 and things works quite well.
I have used templateResult with formatState approach to add the icon to my dropdown options.
$(".js-country-list").select2({
templateResult: formatState
});
ANSWER
Answered 2021-Dec-29 at 12:31The templateSelection
method described at https://select2.org/selections can be used to achieve this, it can be passed the same function used by templateResult
.
$(".js-country-list").select2({
templateResult: formatState,
templateSelection: formatState
});
Example listing countries and their flags (not currencies) is incorporated below.
// Template function which adds CSS flag and displays country name
function flagTemplate(country){
return $("" + country.text + "");
}
// Generate correct URL based on entered search term
function generateUrl(params){
if(params.term){
return "https://restcountries.com/v3.1/name/" + params.term;
} else {
return "https://restcountries.com/v3.1/all";
}
}
// Initialise select2 using flagTemplate function for both result and selection
$('#countrySelect').select2({
// Set template for results and selection
templateResult: flagTemplate,
templateSelection: flagTemplate,
// Set placeholder text
placeholder: 'Select country...',
// Load country list from https://restcountries.com
ajax: {
url: generateUrl,
cache: 250,
dataType: "json",
processResults: function(data) {
return {
results: data
.map(x => ({id: x.cca2.toLowerCase(), text: x.name.common}))
.sort((a, b) => ('' + a.text).localeCompare(b.text))
};
}
}
});
#countrySelect {
width: 300px;
}
.flag-text {
margin-left: 10px;
}
QUESTION
I was able to change the background color of the selected option but it changes its color after I have hovered over any other option.
Is there a way to control this and how can I get rid of this annoying space between the results search-box and container even though it doesnt appear in the code snippet.
The code
#bap + .select2 .select2-selection__rendered {
background-color: yellow;
}
/* Each result */
#select2-bap-results {
background-color: salmon;
}
/* Higlighted (hover) result */
#select2-bap-results .select2-results__option--highlighted {
background-color: rgb(5, 27, 27) !important;
}
/* Selected option */
#select2-bap-results .select2-results__option[aria-selected="true"] {
background-color: rgb(13, 14, 14) !important;
}
/* Around the search field */
.select2-search {
background-color: orange;
}
/* Search field */
.select2-search input {
background-color: pink;
}
Alabama
Wyoming
Wyoming
Wyoming
Solution for the annoying "blank space"
Added more line height to the element
#bap + .select2 .select2-selection__rendered {}
ANSWER
Answered 2021-Dec-19 at 16:43You can add this CSS to change the selected option background color that appears with the gray background: (I simply used green for the example)
#select2-bap-results .select2-results__option--selected {
background-color: green;
}
That change applied to the runnable example below:
#bap + .select2 .select2-selection__rendered {
background-color: yellow;
}
/* Each result */
#select2-bap-results {
background-color: salmon;
}
/* Higlighted (hover) result */
#select2-bap-results .select2-results__option--highlighted {
background-color: rgb(5, 27, 27) !important;
}
/* Selected option */
#select2-bap-results .select2-results__option[aria-selected="true"] {
background-color: rgb(13, 14, 14) !important;
}
/* Around the search field */
.select2-search {
background-color: orange;
}
/* Search field */
.select2-search input {
background-color: pink;
}
#select2-bap-results .select2-results__option--selected {
background-color: green;
}
Alabama
Wyoming
Wyoming
Wyoming
QUESTION
I am setting up a questioner for some of my students and i am stuck.
I have several questions i need to ask my students. All the questions being yes/no questions being selected from a dropdown. "No" will always remain 0 but "Yes" will have a figure somewhere between 0-100 for each question. I am trying to add those selected values to sum them to a total so i can display a score/result.
I have attached the HTML and JS to sum the values from each of the dropdowns (All fine until here).
function submit() { let total=0; document.querySelectorAll('select').forEach(element => { total += parseInt(element.value); }); console.log(total); }
console.log = function(message) {
document.getElementById('result').innerHTML = message;};
console.log('');
1. Did you attend summer training?
NO
YES
2. Have you passed all your grades?
NO
YES
3. Have you completed summer assignments?
NO
YES
Submit
My final hurdle is depending on the end result 'that is when i hit submit' i want to show a specific div with some text on it right below the result/score for each score range (ie any result between 0-20,20-40,40-60,60-100). So for example if the result falls between 20-30. I want to show up a specific div below the result which will have some explainer text on it and the rest of the divs for each score range be hidden.
I am not well versed in JS and would appreciate some help or guidance. I have added my code for reference
ANSWER
Answered 2021-Dec-10 at 20:34If you want to pre-define the text in html you could do so like this:
HTML
some text
some text
some text
some text
CSS:
.hidden { display: none; }
then you just remove the class "hidden" from the desired target, with JS:
document.getElementById("40-60").classList.remove("hidden")
QUESTION
I make autocomplete tags on rails with Select2.js Client and rails code perfectly works, if tags exsist. But if I want to create or add new tag it breaks. I can create tags, but it still makes error, along ids I get new named. but I can't change params
document.addEventListener('turbolinks:load', selectTags)
$(document).ready(selectTags)
function selectTags() {
$('#post_tag_ids').select2({
createTag: function (params) {
return {
id: $.trim(params.term) + '#(new)',
text: $.trim(params.term)
}
},
ajax: {
url: '/tags/search',
dataType: 'json',
delay: 200,
data: function (params) {
return {
q: params.term
}
},
processResults: function (data, params) {
data.map(v => {v.text = v.name})
return {
results: data
}
},
cache: true
},
tags: true,
minimumInputLength: 2,
maximumInputLength: 20
})
}
Simple Post (tags owner) controller:
def create
@post = Post.new(post_params)
set_post_defaults
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: "Post was successfully created." }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def post_params
params.require(:post).permit(:category_id, :title, :content, :tag_list, :tag, { tag_ids: [] }, :tag_ids)
end
ANSWER
Answered 2021-Nov-19 at 09:32My current decision
before_action :create_new_tags, only: [:create, :update]
.
.
.
def create_new_tags
key = "#(new)"
tag_ids = []
params[:post][:tag_ids].each_with_index do |tag_id, index|
next if tag_id.empty?
if tag_id.include?(key) then
tag = Tag.find_or_create_by(name: tag_id.sub(key, ""))
tag.save if !tag.id
else
tag = Tag.find(tag_id.to_i)
end
tag_ids << tag.id.to_s
end
params[:post][:tag_ids] = tag_ids
end
.... and after small refactoring for rubocop:
def create_new_tags
params[:post][:tag_ids].each_with_index do |tag_id, index|
next unless tag_id.include?("#(new)")
tag = Tag.find_or_create_by(name: tag_id.sub("#(new)", ""))
tag.save unless tag.id
params[:post][:tag_ids][index] = tag.id.to_s
end
end
Actual version here
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install select2
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page