Coder Social home page Coder Social logo

bluzky / nice-select2 Goto Github PK

View Code? Open in Web Editor NEW
322.0 4.0 56.0 613 KB

A lightweight vanilla javascript library that replaces native select elements with customizable dropdowns

Home Page: https://bluzky.github.io/nice-select2/

License: MIT License

JavaScript 60.90% SCSS 39.10%
vanilla-javascript select select2 nice-select nice-select2

nice-select2's Introduction

Nice Select

A lightweight Vanilla JavaScript plugin that replaces native select elements with customizable dropdowns.

Install

npm i nice-select2

Usage

Include nice-select2 script.

<script src="path/to/nice-select2.js"></script>

Include the styles, either the compiled CSS...

<link rel="stylesheet" href="path/to/nice-select2.css" />

Or import nice-select2 using ES6 syntax

import NiceSelect from "nice-select2";
@import "~nice-select2/dist/css/nice-select2.css";
// or
@import "~nice-select2/src/scss/nice-select2.scss";

Finally, initialize the plugin.

Using the minimified file directly:

NiceSelect.bind(document.getElementById("a-select"), {searchable: true, placeholder: 'select', searchtext: 'zoek', selectedtext: 'geselecteerd'});

Using as import in webpack:

new NiceSelect(document.getElementById("a-select"), {searchable: true});

Instance method

  • update() : update nice-select items to match with source select
  • focus(): open dropdown list and focus on the search box if search is enabled
  • disable(): disable select
  • enable(): enable select
  • destroy(): destroy NiceSelect2 instance
  • clear(): clear all selected options

Full documentation and examples at https://bluzky.github.io/nice-select2/.

nice-select2's People

Contributors

bluzky avatar dependabot[bot] avatar github-actions[bot] avatar janstieler avatar kodie avatar nicolasmn avatar rpodsada avatar tfeuerst avatar tsjippy avatar wise1999 avatar ybelenko avatar zaru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

nice-select2's Issues

Bootstrap integration?

I'm wondering if style integration with Bootstrap is something suitable for this library.

Support for "required" attributes.

I've implemented this in a project, but when I wanted to add validation to a form field using NiceSelect2, it turned out that the required attribute from the input isn't implemented in a way that makes the input validatable.

The "required" is kept on the original select, which is hidden, which in turn causes the following error when the form is submitted:

An invalid form control with name='customer[note][Veterinarian]' is not focusable.

It would be great if this library implemented this (baseline feature of HTML) in some way!

Module not found: Error: Can't resolve 'window' in '/app/node_modules/nice-select2/dist/js'

Hi, i'm trying out this plugin with webpack.

Trying both of these options and both are not working.
import { NiceSelect } from "nice-select2";

import NiceSelect from "nice-select2";

full errorlog:

Compiled with problems:

ERROR in ./node_modules/nice-select2/dist/js/nice-select2.js 1:82-99

Module not found: Error: Can't resolve 'window' in '/app/node_modules/nice-select2/dist/js'

I saw these files where minified so maybe you can take a look at this :)

Hitting "return/enter" key submits the form instead of selecting an option in search.

As above. In other single/multi select fields, hitting enter selects the option. In Nice-Select2, it submits the form. There should be a way to prevent this from happening. For the moment I'm just using my own solution:

	NiceSelect.bind(
		document.getElementById('property_location'),
		{searchable: true, placeholder: 'Search'}
	);

	const searchForm = document.getElementById('property-search-form');
	
	searchForm.addEventListener('submit', function(e) {
		if ( searchForm.querySelector('.nice-select-search:focus') ) {
			e.preventDefault();
			document.getElementById("PrimarySubmit").focus();
		}
	});

Which works fine, but I feel like this should be the default...

Use arrow keys to navigate up and down when overflow-y is scrollable

So, the _onKeyPressed function selects the next element, but if there is overflow-y scroll applied to the ul list,
it doesn't move the position with keycode = 38 and keycode = 40. User needs to use mouse to acually scroll thru list.

This is something that would be very nice to have :)

Many thanks!

Ivana

nice-select2

Missing Typescript support

๐Ÿ› Problem

This library lacks of Typescript support, so when working with typescript:

  • Intellisense does not work
  • bind function gets erroneously recognised as the Function.prototype.bind one

๐Ÿ’ป Workaround

To integrate it with my environment I had to write my own declaration file.

Just put the following content in any .d.ts file:

// src/types/niceSelect.d.ts

export declare global {
	declare module NiceSelect {
		/**
		 * Creates a new instance of the NiceSelect select UI.
		 * 
		 * `NiceSelect.bind(element, options)` is an alias for `new NiceSelect(element, options)`
		 * @param element The target HTMLElement
		 * @param options An object containing all the options
		 */
		export function bind(element, options?: niceSelectOptions): NiceSelect;
		
		/**
		 * **Nice Select 2**
		 * 
		 * A lightweight vanilla javascript library that replaces native select 
		 * elements with customizable dropdowns.
		 * @see https://bluzky.github.io/nice-select2/
		*/
		export class NiceSelect {
			/**
			 * Update nice-select items to match with source select
			 */
			update(): void

			/**
			 * Disable the select
			 */
			disable(): void
			
			/**
			 * Enable the select
			 */
			enable(): void
			
			/**
			 * Destroy the NiceSelect2 instance
			 */
			destroy(): void
			
			/**
			 * Clear all selected options
			 */
			clear(): void
		}
	}
}

type niceSelectOptions = {
	/**
	 * Pass the data option to explicitly create **custom options**.
	 * 
	 * If the `data` option is present, then all existing options
	 * on the HTML Select will be ignored.
	 */
	data?: {
		/**
		 * Specify the text to be shown on the option.
		 */
		text: string,

		/**
		 * Specifies the value of the option element:
		 * - If set to `"optgroup"`, the element will be rendered as a select "Option Group".
		 * - If set to `string`, this will be the value of the option.
		 */
		value: "optgroup" | string
	}[],

	/**
	 * Wether the Select should support **search autocomplete**.
	 */
	searchable?: boolean
}

Add option to change search placeholder

It would be very useful to add the possibility to change the default text for the input element used to search when searchable is set to true.

As of now it shows only "Search...", which is not ideal when i need to customize the i18n of the app.
image

It could be something like this...
image

I could provide a PR for this, since i think i'll either way fork this project and add the changes i need ๐Ÿ˜„

Cascading Dropdown list

How can i make cascading dropdown list with nice select? I couldn't figure it out and couldn't find any example :(

multiple not working

I really like this library.
Thank you.
I hope you still maintain it.

This does not work for selects with the multiple keyword.
You get this error:

Uncaught TypeError: this.selectedOptions.each is not a function at a.updateSelectValue (nice-select2.js?ver=6.9.207:1) at a._onItemClicked (nice-select2.js?ver=6.9.207:1)

ANd the value of the original select is not updated

null value in classList

Line 241 to 245

because of this, pushing null value to classList

var classList = [
  "option",
  option.attributes.selected ? "selected" : null,
  option.attributes.disabled ? "disabled" : null,
];

Fixes

var classList = ["option"];

if (option.attributes.selected) classList.push("selected")
if (option.attributes.disabled) classList.push("disabled")

Selected option is not shown on component build

If you change, in the extractData method from this:
var o = {
selected: e.getAttribute("selected"),
disabled: e.disabled,
optgroup: "OPTGROUP" == e.tagName
};

to this:
var o = {
selected: null != e.getAttribute("selected"),
disabled: e.disabled,
optgroup: "OPTGROUP" == e.tagName
};

you fill not get this issue.

Cant type space in search bar

When there are options available, space will select the option and scroll the page down.
So user cant search with multiple words if there are matches
if you type some option in the demo page, it will close the dropdown and scroll down after you type some

updateSelectValue multiple issue

When user check and uncheck item, in native select, option doesn't remove attribute selected=true.

You can fix it by:

var select = this.el;
select.querySelectorAll("option").forEach(function (item) {
  item.removeAttribute("selected");
});
this.selectedOptions.forEach(function(item) {
  var el = select.querySelector(`option[value="${item.data.value}"]`);
  if (el){
    //Change it, cause it works more correctly.
    el.setAttribute("selected", "selected");
    el.selected = true;
  }
});

Or some better solution with indexOf, filter.

HTML5 validation broken

Unfortunately HTML5 validation is not working, if the initial select element has a required attribute, because it's hidden. The browser will fail with an error An invalid form control with name='fieldname' is not focusable.

Instead of hiding the element, we could apply a similar fix as described in Choices-js/Choices#449.

overflow text

if have an option with a long text
the display will be like this

image

FR: add event when you open/close the niceselect

Hi,
We are using both single and multiselects and I want to submit a form when something changes. For single selects this can easily be done by listening to the change event of the original select, but for multiselects this would be triggered on the first change, but instead I want to react once the pulldown is closed. I should actually monitor if something has changed while the nice-select is opened and trigger the submission once the niceselect is closed.

Could you please add an event when the nice select opens and another event when it gets closed.

And if you want to be super handy you could fire an event for both single and multiselects if something has changed on close. That would, for example, prevent event triggering when the same option is selected and unselected again in a multiselect and closed.

Thanks!

Issue with importing package through ES6 notation

Hello,
I've installed the package through NPM and I'm trying to import it in my project, but when I try to

import * as ns from "nice-select2"
window.NiceSelect = ns;

I get a "Package is not installed" error.
The package is present in the node_modules directory.

My stack is Vite v4.3.8 and Tailwind 3.3.2
This is the full error log, I think something in the manifest or exports could be wrong.

9:57:06 AM [vite] Internal server error: Failed to resolve entry for package "nice-select2". The package may have incorrect main/module/exports specified in its package.json.
Plugin: vite:import-analysis
File: /var/www/html/resources/js/app.js
at packageEntryFailure (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:23382:11)
at resolvePackageEntry (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:23379:5)
at tryNodeResolve (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:23113:20)
at Context.resolveId (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:22874:28)
at async Object.resolveId (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:42847:32)
at async TransformContext.resolve (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:42575:23)
at async normalizeUrl (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:40500:34)
at async file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:40651:47
at async Promise.all (index 7)
at async TransformContext.transform (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-4d3eff22.js:40577:13)

Can't import the library because of wrong "main" entry in package.json

Hi, you have an error in your package.json

{
  "name": "nice-select2",
  "version": "2.1.0",
  "description": "A lightweight Vanilla JavaScript plugin that replaces native select elements with customizable dropdowns.",
  "main": "src/js/nice-select.js",
  "directories": {
    "doc": "docs"
  }
  ...

You're pointing to src/js/nice-select.js but the file is acutally named nice-select2.js this leads to issue when I try to import the library using webpack.

Add title on search input for accessbility

The search box on searchable menus does not have a label and is flagged by some accessibility audits. Adding a title attribute to the input element would make the feature more accessible for screen readers.

Support for multiple as a boolean attribute

Since multiple attribute is a boolean attribute, it should be set like this: <select multiple>.
But nice-select only enables its multi functionality if I set it in this outdated manner <select multiple="multiple">.

Customize texts

It would be nice if one could customize texts like "Select an option", "Search...", "X selected"

Purpose of data-display?

Looking at the example on https://bluzky.github.io/nice-select2/, the data-display functionality does not work.

From my understanding, it allows the user to provide alternative text to use when the option is selected. If this is the case, the example should show "Select" when the "Nothing" option is chosen. Not sure if I am misunderstanding this feature, but some clarification would be helpful

Thanks

window.onclick in another javascript file causing problems for nice-select2's _onClicked handler

I'm having difficulty integrating nice-select2 into a project.

I know this has to be a bug in my code and distilling it down to a simple reproducible example would be difficult. I'd be willing to pay for some support if it's available.

I have an async function that is dynamically generating html based on user input. It's async because some of the select controls need to call fetch() to get their content.

At the end of that function, it checks if any select2 controls were generated and triggers a setTimeout with a delay of 100. This was necessary because select2 couldn't even find the elements if I do it quicker.

Inside the setTimeout callback I'm triggering NiceSelect. I know it's at least partially working but the control transforms into a select2 styled control, but when I click on it, nothing happens and I get no errors in the console.

Here's the snippet where I invoke setTimeout:

		if( has_select2 )
		{
			setTimeout( function()
			{
				let options = { searchable: true }
				let els = Array.from( document.getElementsByClassName( 'ace_select2' ))
				for( let el of els )
				{
					console.log( 'select2 binding: ', el )
					NiceSelect.bind( el, options )
				}
			}, 100)
		}

Scrollbar in list of values?

Hello, is it possible to display scrollbar in dropdown list? I find it very un-intuitive if there are more values than visible and no scrollbar to indicate so. But any tries to set overflow to scroll failed, scrollbar is never showing up. What am I doing wrong?

Thank you

Any way to remove the dropdown animation / transition?

I've tried removing the dropdown transition effect in CSS, which does remove the animation. But, it seems like due to the intermediate transition styles, the post-transition styles don't get applied for a noticeable delay. I couldn't find any docs for tweaking that.

The main problem I have is that the transition entrance animation feels sluggish. If possible I'd like it to show instantly. Not sure if there's some JS logic that is delaying the dropdown from showing.

Adjust min-height of select element

After nice-select2 init, the select element receives inline styles, but it lacks a min-height property.

When the select element has a min-height property, its height is not equal to 0.

The min-height value should be set to auto.

"lightweight Vanilla JavaScript plugin" and Jquery in dependencies

Hi, thanks for cool project.

Readme claims that this library are lightweight Vanilla JavaScript plugin, but it depends on jquery.
I'm not a JS developer, but seems really strange to me, it can be either "lightweight Vanilla", or it can depends on jquery, IMHO.

Thanks!

Feature request: Option to retain data attributes

Currently when the select initialises, it strips out the data attributes which causes a bit of a headache if we rely on them. Can I request that data attributes are retained or an option is added for us to specify which attributes are filtered?

Clean up your package

Hi,
you have a lot of .DS_Store files in your NPM package.
They can have unwanted effect on a local installation.

Cheers

Support for height: auto;

I have a long option that breaks into a second line, so I cannot set a fixed $input_height. But when I try to set $input_height to auto I get the following warning on the console:

Warning: math.div() will only support number arguments in a future release.
Use list.slash() instead for a slash separator.

Its because of the following code
transform: scale(.75) translateY(- math.div(-$input-height, 2));
out of https://github.com/bluzky/nice-select2/blob/master/src/scss/nice-select2.scss#L126

listening for 'input' event on original select control does not working with nice-select2

I'm currently registering for 'input' events on the that I create before calling NiceSelect.bind(): input.addEventListener( 'input', onChange ) This event was working before I started trying to use NiceSelect, now it has stopped working. It appears to be caused by the fact that NiceSelect is not updating the original element whenever the selection is changed in the replacement control.

reset selection

how to reset selection or select the drop down use call function? already tried to call like usually we call value by id use jquery, the problem is it changed on native drop down only..not the new drop down means value is correct change but not in the ui. I still saw the prev selection.

extractData when page is reloaded

Hi !
Thanks for your nice select !
I can suggest you to use the javascript properties instead of html attributes in your extractData method.
If you refresh your page and you have selected some options in your select form. your options are not coded in the html attributes but are clearly visible to the user and accessible with javascript.

file : src/js/nice-select2.js#L119

    var attributes = {
-      selected: item.getAttribute("selected") != null,
+      selected: item.selected,
-      disabled: item.getAttribute("disabled") != null,
+      disabled: item.disabled,
       optgroup: item.tagName == 'OPTGROUP'
    };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.