Select: Limit number of selected options - select

I'm using ANT Design's Select component in multiple select mode. After two options are selected (see screenshot) I'd like to prevent any more from being selected. The field should not be disabled, so that you can deselect an option and select another.
I've tried the onFocus event, but it doesn't provide an event that I could use to preventDefault or otherwise keep from opening the dropdown. I've also tried adding a ref and calling blur() whenever the onFocus event is called. This closes the dropdown, but it's still visible for a second.
Does anyone know of a way to accomplish this?

If 3 or more options selected then with a simple condition you can disable other options.
Store selected options in state and while displaying options disable them based on condition.
https://codesandbox.io/s/happy-leftpad-lu84g
Sample code
import React, { useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const opts = ["a11", "b12", "c13", "d14", "e15"];
const Selectmultiple = () => {
const [optionsSelected, setOptionsSelected] = useState([]);
const handleChange = value => {
console.log(`selected ${value}`);
setOptionsSelected(value);
};
return (
<div>
<Select
mode="multiple"
style={{ width: "100%" }}
placeholder="Please select"
onChange={handleChange}
>
{opts.map(item => (
<Option
disabled={
optionsSelected.length > 1
? optionsSelected.includes(item)
? false
: true
: false
}
key={item}
>
{item}
</Option>
))}
</Select>
</div>
);
};

I solved this problem using "open" prop:
const isMaxValues = value.length === limit;
<Select
mode="multiple"
disabled={false}
{...(isMaxValues && { open: false, onDropdownVisibleChange: handleShowError })}
>
{renderOptions()}
</Select>
So you still able to remove/deselect some options
Also you can provide isMaxValues option to renderOptions method and disable Options to be selected(if you need dropdown to be visible)

Related

Material UI select dropdown arrow keys navigation not working

I added a textfield inside mui multiple select component , now keyboard arrow up and down list navigation is not working instead,on arrow onkeydown it focuses on the div itself (scrolling on arrow keydown).
Any help is appreciated (AutoComplete is not an option)
Have tried adding autoFocus on MenuItem itself , but that starts from the last list
import * as React from "react";
import { Theme, useTheme } from "#mui/material/styles";
import MenuItem from "#mui/material/MenuItem";
import TextField from "#mui/material/TextField";
import FormControl from "#mui/material/FormControl";
import Select, { SelectChangeEvent } from "#mui/material/Select";
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 250
}
}
};
const names = [
"Oliver Hansen",
"Van Henry",
"April Tucker",
"Ralph Hubbard",
"Omar Alexander",
"Carlos Abbott",
"Miriam Wagner",
"Bradley Wilkerson",
"Virginia Andrews",
"Kelly Snyder"
];
function getStyles(name: string, personName: string[], theme: Theme) {
return {
fontWeight:
personName.indexOf(name) === -1
? theme.typography.fontWeightRegular
: theme.typography.fontWeightMedium
};
}
export default function MultipleSelect() {
const theme = useTheme();
const [personName, setPersonName] = React.useState<string[]>([]);
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
const {
target: { value }
} = event;
setPersonName(
// On autofill we get a stringified value.
typeof value === "string" ? value.split(",") : value
);
};
return (
<div>
<FormControl sx={{ m: 1, width: 300 }}>
<Select
multiple
value={personName}
onChange={handleChange}
MenuProps={MenuProps}
onKeyDown={(e) => {
if (e.key !== "Escape") {
e.stopPropagation();
}
}}
>
<div style={{ textAlign: "center", margin: "20px 0px" }}>
<TextField placeholder="type..." />
</div>
{names.map((name) => (
<MenuItem
key={name}
value={name}
style={getStyles(name, personName, theme)}
>
{name}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
}
It seems the issue is that the TextField element is a child of the Select element and is intercepting the keydown events that would normally be used to navigate the list of options. One way to fix this would be to use the onKeyDown prop on the TextField element to prevent it from intercepting the keydown events. Instead of calling e.stopPropagation(), you can call e.preventDefault() which will prevent the event from being handled by the TextField element and allow it to be handled by the Select element.
<TextField placeholder="type..." onKeyDown={e => e.preventDefault()}/>
Also to make sure that focus is on the first element in the list after the user opens the list you can use autoFocus prop on the first element of the list.
<MenuItem
key={names[0]}
value={names[0]}
style={getStyles(names[0], personName, theme)}
autoFocus
>
{names[0]}
</MenuItem>
This should allow the arrow keys to navigate the list as expected, while still allowing the user to type into the TextField.

building a basic search bar Material-UI

I want to build a really basic search bar with a search icon (similar to the one on Material-UI ) & invoke a function with the current value of the search field whenever the user hits enter or click on the search enter. I am new to Material-UI & I'm struggling to find my way through the different text fields elements.
I currently have this code
import Input from '#material-ui/core/Input';
class ...somecode
...somecode
constructor(props) {
super(props);
this.state = {
resources: [],
value: '',
};
}
handleChange(event) {
console.log(event.target.value);
this.setState({ value: event.target.value });
}
search(/* access value upons enter/ search icon click */) { <--------------------------
}
...some code
return (
<form id="search">
<Input type="text" value={value} onChange={(event) => { this.handleChange(event); }} placeholder="Search..." autoFocus fullWidth />
</form>
);
p.s: I had a really hard time fiddling around with all the APIs and options available in the input suite (I highly suggest an explanation of how they are related in the docs)

Angular 6 reset select options onclick

I am trying to reset options value when clicked on button. I was unable to find any solution. I have a component where I am using this code:
<select class='select-option' required [(ngModel)]='optionSelected' (ngModelChange)="toNumber()">
<option [ngValue]="undefined" disabled selected> Please select one option </option>
<option *ngFor='let option of options' [ngValue]="option">{{option}}</option>
</select>
Inside my class I am using this code:
options = ["Bar", "Pie", "Area"];
To call options inside a loop. I am using this code on button event:
appendToContainer(){
// logic
this.options == null
}
What should I do to make it default or null
Your logic is correct, but implementation is wrong:
appendToContainer(){
// logic
this.options == null; // ==> WRONG expression
this.options = []; // ==> CORRECT
}
Try this:
appendToContainer(){
// logic
this.options.value == this.options.options.first;//if the first options is 'Select'
}

Angular2 default 'selected' select option not being set

I am having an issue getting select boxes on my Angular2 application to show a default option '--please select--' on page load. I have managed to get this working before but I cannot seem to get this working in this particular instance. I'll show my code then explanations as I show it.
Here is my relevant controller code:
import {Component} from "#angular/core";
import {ProductService} from "../../services/product.service";
import {Subscription} from "rxjs";
import {ActivatedRoute} from "#angular/router";
#Component({
selector : 'product',
moduleId : module.id,
templateUrl : '/app/views/products/product-view.html'
})
export class ProductComponent {
private id:number;
private _subscription: Subscription;
public product;
private price;
private quantity = 0;
constructor(
private _productService: ProductService,
private _activatedRoute: ActivatedRoute
) {
}
getProduct(productId: number) {
this._productService.getProduct(productId)
.subscribe((response) => {
response.success.product.options.forEach((option) => {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
option.product_option_value.unshift({
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
});
});
this.product = response.success.product;
this.generatePrice();
});
}
changeOption(optionValueId, option) {
if(optionValueId != 0) {
let selectedOptionValue = option.product_option_value.filter((option) => {
return option.product_option_value_id == optionValueId;
});
this[option.name] = selectedOptionValue[0];
} else {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
}
this.generatePrice();
}
.....
Here I am getting back information about a product which includes 'options' in a form of an array. This array of objects is iterated over to create the select boxes in the view code which will come later. I add a default '-- please select --' object for each option and put it to the front of the array using unshift. I then also set the controller value for this in the line:
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
rice_prefix: '+'
};
The relevant view code is as follows:
<div class='product-options'>
<div class='option' *ngFor='let option of product.options; let i = index'>
<p class='option-name' [innerHTML]='option.name'></p>
<select name='option.name' [ngModel]='option.name' (ngModelChange)='changeOption($event, option)' required>
<option *ngFor='let productOptionValue of option.product_option_value; let j = index;' [value]='productOptionValue.product_option_value_id'>{{ productOptionValue.name }}</option>
</select>
</div>
<div class='price' ngDefaultControl [(ngModel)]="price">{{ price | currency:'GBP':true:'1.2-2' }}</div>
<div class='add-to-basket-wrap'>
<button class='add-to-basket'>add to basket</button>
<button class='increment' (click)="changeQuantity('down')">-</button>
<input type='text' name='quantity-to-add' [(ngModel)]="quantity" (click)='addToBasket()' />
<button class='increment'(click)="changeQuantity('up')">+</button>
</div>
</div>
Here I loop through the options then through the values for these options to generate the select boxes. I set the [ngModel] attribute for the select to the same as the one that was saved in my controller. I was under the impression that Angular2 would detect this binding, spot the value was the same as the controller value and then automatically set that as the 'selected' default option.
Can anyone see why this isn't working?
Thanks
Looks like your code is not working because your template and your class are not binding to the same properties.
In your component template, when you write this:
<div *ngFor="let option of product.options; let i = index">
<select [ngModel]="option.name">...</select>
</div>
... you're effectively binding each <select> to a class property named product.options[i].name.
On the other hand, in your component class, when you write this:
changeOption(optionValueId, option) {
this[option.name] = selectedOptionValue[0];
}
... you're writing to a class property named after whatever string is contained in option.name, e.g. foo.
As you can see, product.options[i].name and foo don't match. Even by changing foo to another string, you won't be able to access the property you want.
A few remarks/questions that might help:
It's a bit strange to store options inside "dynamic" class properties — this[option.name] = .... Why not store them in a dedicated this.options property that you can declare, type, and log out for debugging purposes: this.options[option.name] = ....
Why did you decide to use <select [ngModel]="..." (ngModelChange)="..."> vs the more compact <select [(ngModel)]="...">?
Any reason why you're using simple quotes on your HTML attributes, e.g. <div class='price'> vs <div class="price">? This is not the usual style.

How to manage DOM element dependencies

I am trying to create a web-page where some elements (forms and buttons) become visible or are being hidden when some other elements (buttons) are clicked.
I try to find a way to manage this, that is re-usable, and easy to maintain.
My current solution is shown below, but I hope someone has a more elegant solution.
The problem with my own solution is that it will become difficult to read when the number of dependencies increase. It will then also require a lot of editing when I add another button and form.
My current solution is to use an observable to manage the state of the forms, like this:
HTML:
<button id="button-A">Show form A, hide button A and B</button>
<button id="button-B">Show form B, hide button A and B</button>
<form id="form-A">
...this form is initially hidden
...some form elements
<button id="cancel-A">Hide form A, show button A and B</button>
</form>
<form id="form-B">
...this form is initially hidden
...some form elements
<button id="cancel-B">Hide form B, show button A and B</button>
</form>
Dart:
import 'dart:html';
import 'package:observe/observe.dart';
final $ = querySelector;
final $$ = querySelectorAll;
Map<String, bool> toBeObserved = {
"showFormA" : false,
"showFormB" : false
};
// make an observable map
ObservableMap observeThis = toObservable(toBeObserved);
// start managing dependencies
main() {
// add click event to buttons
$('#button-A')
..onClick.listen((E) => observeThis["showFormA"] = true);
$('#button-B')
..onClick.listen((E) => observeThis["showFormB"] = true);
// add click events to form buttons
$('#cancel-A')
..onClick.listen((E) {
E.preventDefault();
E.stopPropagation();
observeThis["showFormA"] = false;
});
$('#cancel-B')
..onClick.listen((E) {
E.preventDefault();
E.stopPropagation();
observeThis["showFormB"] = false;
});
// listen for changes
observeThis.changes.listen((L) {
L.where((E) => E.key == 'showFormA').forEach((R) {
$('#form-A').style.display = (R.newValue) ? 'block' : 'none';
$('#button-A').style.display = (R.newValue || observeThis['showFormB']) ? 'none' : 'inline-block';
$('#button-B').style.display = (R.newValue || observeThis['showFormB']) ? 'none' : 'inline-block';
});
L.where((E) => E.key == 'showFormB').forEach((R) {
$('#form-B').style.display = (R.newValue) ? 'block' : 'none';
$('#button-A').style.display = (R.newValue || observeThis['showFormA']) ? 'none' : 'inline-block';
$('#button-B').style.display = (R.newValue || observeThis['showFormA']) ? 'none' : 'inline-block';
});
});
}
You can use basic CSS to show/hide the elements.
HTML
<div id="container" class="show-buttons">
<button id="button-A" class="btn" data-group="a">...</button>
<button id="button-B" class="btn" data-group="b">...</button>
<form id="form-A" class="form group-a">...</button>
<form id="form-B" class="form group-b">...</button>
</div>
CSS
.btn, .form {
display: none;
}
.show-buttons .btn,
.show-a .form.group-a,
.show-b .form.group-b {
display: block;
}
In Dart just get the data-group (or whatever you want to call this) attribute from the button. Toggle the CSS classes (show-buttons, show-a and show-b) on the container element to switch between the buttons and the specific forms.
This solution is very easy to extend on.
You can use something like this to handle all the elements in a generic way :
final Iterable<ButtonElement> buttons = querySelectorAll('button')
.where((ButtonElement b) => b.id.startsWith('button-'));
final Iterable<ButtonElement> cancels = querySelectorAll('button')
.where((ButtonElement b) => b.id.startsWith('cancel-'));
final Iterable<FormElement> forms = querySelectorAll('form')
.where((FormElement b) => b.id.startsWith('form-'));
buttons.forEach((b) {
b.onClick.listen((e) {
// name of clicked button
final name = b.id.substring(b.id.indexOf('-') + 1);
// hide all buttons
buttons.forEach((b) => b.hidden = true)
// show the good form
querySelector('#form-$name').hidden = false;
});
});
cancels.forEach((b) {
b.onClick.listen((e) {
// show all buttons
buttons.forEach((b) => b.hidden = false);
// hide all forms
forms.forEach((b) => b.hidden = true);
// prevent default
e.preventDefault();
});
});
// hide all form at startup
forms.forEach((f) => f.hidden = true);
You could use polymer's template functionality like
<template if="showA">...
This should work without embedding your elements within Polymer elements too.
This discussion provides some information how to use <template> without Polymer elements.
Using Polymer elements could also be useful.
It all depends on your requirements/preferences.
Angular.dart is also useful for such view manipulation.
If you want to use plain Dart/HMTL I don't have ideas how to simplify your code.