Antd select element: how can I disable typing? - html

I'm trying to use a select element with mode="multiple". I'd like for input to be disabled, meaning that a user can only choose between existing options, not enter text. How do I do this?
My element:
import { Select } from 'antd';
import 'antd/dist/antd.css';
const { Option, OptGroup } = Select;
<Select
defaultValue={['current', 'grower', 'variety', 'varietyP90']}
size={'large'}
style={{ width: '13rem' }}
onChange={value => this.setState({ yield: value })}
mode="multiple"
maxTagCount={0}
maxTagPlaceholder="Yield metrics">
<Option value="current">Current Yield</Option>
<Option value="grower">Grower Average</Option>
<Option value="variety">Variety Potential</Option>
<Option value="varietyP90">All growers' average</Option>
</Select>

Unfortunately in v3.3 there is no way to hide the search input of Select in multiple mode.
We can set the input maxlength to zero and get the wanted result.
The offering solution is kind of a hack and I don't like it personally but I couldn't find any better solution. I tried to hide the input using css but that prevents to close the drop-list because the input is used as a trigger for closing the list on focus lost event.
class TagSelect extends Select {
disableInput() {
const selects = document.getElementsByClassName(`ant-select-search__field`)
for (let el of selects) {
el.setAttribute(`maxlength`, 0)
}
}
componentDidMount() {
this.disableInput()
}
}
ReactDOM.render(
<TagSelect
defaultValue={['current']}
size={'large'}
style={{width: '100%'}}
mode="multiple"
placeholder="Yield metrics"
>
<Option value="current">Current Yield</Option>
<Option value="grower">Grower Average</Option>
<Option value="variety">Variety Potential</Option>
<Option value="varietyP90">All growers' average</Option>
</TagSelect>,
document.getElementById("container")
)
The working demo you can check here.

This is a kind of hack in ant selection component. (using css)
Ant Version: 3.26.6
<Select className="my_select_component" />
.my_select_component {
.ant-select-search__field {
display: none;
}

Related

Getting value of select option in react

I'm using Material UI for my react app and am trying to get the value of a select form.
This works perfectly with the following code:
<select name="role" value={props.role} onChange={props.handleInputChange}>
<option value="client">Client</option>
<option value="worker">Worker</option>
</select>
However, if I try to implement the exact same thing using Material UI
<FormControl margin="dense" className={classes.textFieldSelect}>
<InputLabel htmlFor="role" >Role</InputLabel>
<Select
value={props.role}
onChange={props.handleInputChange}
input={<Input id="role" />}
>
<MenuItem value="worker">Worker</MenuItem>
<MenuItem value="client">Client</MenuItem>
</Select>
</FormControl>
Here's the code for handInput change in my parent component:
handleInputChange(e) {
e.preventDefault();
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({ currentUser: { ...this.state.currentUser, [name]: value } });
}
The value of the select bar doesn't change when I click the menu items. However, the values do change in the TextField if I select a different role in the plain HTML element.
Any clues on what I am doing wrong?
I just spent some time debugging it and it turns out that the reason it didn't work is because the e.target.name property is undefined when I click the . I can fix this by passing in a specific name parameter when I call handleInputChange (e.g. handleInputChange('role')). Thanks for looking at it though!

Searchable select element in React

I'm trying to build searchable select element in React. What is really important to me is:
Avoide jQuery
Posibility to set one of options as default selected
I have list of options, which now looks like that:
<select
onChange={props.onChange}
id={props.id}
className={props.style || "form-control"}>
{!props.defaultOption ?
<option value="" selected>Select</option> :
<option value={props.defaultOptionValue} disabled selected>{props.defaultOption}</option>}
{props.options.map((item, i) => {
if (item.id === props.defaultOptionValue) return false;
return <option key={i} value={item.id}>{item.name}</option>
})}
</select>
Nothing really complicated. I pass onChange handler, id and styles. If i provide defaultOptionValue and defaultOption in props, then it means i need to check this one as selected.
Datalist works great for me, but it doesn't support safari and i want to display label inside my input, not a value, as value is id and label name of the object.
I have already checked react-select, but it's missing option to set default value.

How can I display option text on the dropdown menu that is different than the selected text?

Using a simple select, I want to display one text on the dropdown list and another text in the select control after the option was selected. It's pretty similar to option's label attribute in its concept.
I'm not sure if it's even possible. Here's a not-working example:
<select>
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
Update: I didn't mention that I need to incorporate this solution in a generated HTML (ng-table filters), so any solution that is not pure HTML will be very hard to use. I even consider to look for another table control as a simpler solution, which is pretty basic - placeholder text in select filter.
I've created a question more specific to my problem:How can I put a placeholder text on ng-table select filter?
Here's a relatively simple solution that relies on the standard value attribute and a custom data-* attribute:
function showDisplayValue(e) {
var options = e.target.options,
option = e.target.selectedOptions[0],
i;
// reset options
for (i = 0; i < options.length; ++i) {
options[i].innerText = options[i].value;
}
// change the selected option's text to its `data-display` attribute value
option.innerText = option.getAttribute('data-display');
}
document.getElementById('foo').addEventListener('change', showDisplayValue, false);
<select id="foo">
<option data-display="*** BAR ***" value="Bar">Bar</option>
<option data-display="*** BAZ ***" value="Baz">Baz</option>
<option data-display="*** QUX ***" value="Qux">Qux</option>
</select>
Found something similar to what you're asking for here:
https://stackoverflow.com/a/19184179/6555780
It basically needs to be organised in javascript, so that the selected option shows immediately on the screen, the below code was taken from David's answer and can be viewed here: http://jsfiddle.net/aCb73/
<select name="ref_rubrique" id="ref_rubrique">
<option value="-- EMPTY --" selected> </option>
<option value="YES!!!">Yes</option>
</select>
<div id="ref_output"></div>
<script type="text/javascript">
var selectElement = document.getElementById('ref_rubrique');
var divElement = document.getElementById('ref_output');
selectElement.onchange = function () {
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue == '-- EMPTY --') {
divElement.innerHTML = '<p>No</p>';
} else if (selectedValue == 'YES!!!') {
divElement.innerHTML = '<p>Yes</p>';
}
};
</script>
This basically targets the ref_rubique select tag and displays the code in the Javascript based on the selection (defaults as --EMPTY--)
Following our comments below, the following code could possibly help with ng-table:
self.initialSorting = [
{ label: "Id ASC", value: { id: "asc"} },
{ label: "Id DESC", value: { id: "desc"} },
{ label: "Name ASC", value: { name: "asc"} },
{ label: "Name DESC", value: { name: "desc"} }
];
What I understand is you want to print the text in select-text attribute.
I've found this example if this is what you are looking for.
<select id="mySelect">
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
$("#mySelect").change(function(){
$("#mySelect option:selected").text($("#mySelect").val());
});
This is where I found something similar.
HTML select shows value instead of text

HTML tags to allow user to select multiple items and set their order

I have this input to allow user to select (with multiple choices) a product:
<select multiple="yes" name="products[]">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>
</select>
User can select several stuff in that list, and I can get in server-side using, for instance, PHP:
$_GET['products'] ← array('wood', 'iron', 'food');
Now, I would like to allow users to specify an order for the selection they made. So, I want the user to be able to not only set the list of items to select (like a <select multiple="yes">) but also in which order I will treat them.
In other words, let's say a user want the list to be ordered to:
$_GET['products'] ← array('gold', 'iron', 'wood', 'dust');
Currently, using the <select multiple="yes"> I can only ask user to unorderedly pick up items from a list but
what's the HTML tags I should use to allow user to select multiple options and specify its order?
I don't want to sort the options inside the <select>, I want the user to be able to tell the server in which order it should treat the selected items list.
I picked PHP example as server-side treating code (and it's the language I will use) but actually, the answer should not rely on server side language: I'm looking for the "html-client-side" code to use.
The following answer isn't exactly elegant but it get's the job done. I havn't been doing Web development long but I'm learning.
The JavaScript could be better as I'm used to jQuery (crutch I know).
Pure js (easier if you can use jQuery)
var products = [];
function add(val) {
if (!contains(products, val))
{
products.push(val);
document.getElementById('list').setAttribute('name', products);
}
}
// checks if arr 'a' has the element 'obj'
// thanks to someone at stack overflow for how to do that :)
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
html
// add the onclick='add()' function to your html
<select id='list' multiple="yes" name="" value='heyo'>
<option onclick='add("wood")' value="wood">Wood</option>
<option onClick='add("iron")' value="iron">Iron</option>
<option onClick='add("gold")' value="gold">Gold</option>
<option onClick='add("dust")' value="dust">Dust</option>
<option onClick='add("food")' value="food">Food</option>
</select>
Working jsfiddle here: http://jsfiddle.net/TcGt5/
<!-- language: lang-js -->
<script>
var jproducts = [];
var selectCount= 0;
function myFunction() {
var select = document.getElementById("mySelect");
// test if select value already exist
options = select.getElementsByTagName('option'),
for (var i=options.length; i--;) {
if (options[i].selected)
selectCount +=1;
if (function 'is_not_in_products_array')
jproducts.push(options[i].value)
}
// remove unselected products
for (var j=0; j< (jproducts.length-selectCount); j++;)
jproducts.shift();
}
</script>
Finnaly the products array will containt only the last selected
<select id="myselect" multiple="yes" name="products[]" onchange="myFunction()">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>

html - how can I display images when option from drop down menu is selected

I have the code for a drop down menu:
</center>
<p>
<center><select>
<option value="none">None selected</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
</center></select>
</p>
I want to be able to display an image of a cat (such as http://www.petfinder.com/wp-content/uploads/2012/11/95142833-crate-training-cat-632x475.jpg) when the "cat" option is selected and also alternate text (such as "image of cat could not be loaded") if the image could not be loaded. How can I do this?
you can insert an image on value change in select box, i would do it like this:
html:
<select id="pic-changer">
<option value="none">None selected</option>
<option value="cat" data-picture="cat.png">cat</option>
<option value="dog" data-picture="dog.jpg">dog</option>
</select>
<div id="image-location></div>
jquery (javascript) code:
$('#pic-changer').change(function(){ //if the select value gets changed
var imageSource = $(this).find(':selected').data('picture'); //get the data from data-picture attribute
if(imageSource){ //if it has data
$('#image-location').html('<img src="'+imageSource+'">'); // insert image in div image-location
} else {
$('#image-location').html(''); //remove content from div image-location, thus removing the image
}
})
if you dont need the select box value, I would suggest putting the picture link in there:
<select id="pic-changer">
<option value="">None selected</option>
<option value="cat.png">cat</option>
<option value="dog.jpg">dog</option>
</select>
jQuery code becomes:
$('#pic-changer').change(function(){ //if the select value gets changed
var imageSource = $(this).val(); //get the selected value
if(imageSource && imageSource != ""){ //if it has data
$('#image-location').html('<img src="'+imageSource+'">'); // insert image in div image-location
} else {
$('#image-location').html(''); //remove content from div image-location, thus removing the image
}
})
You can do much more with javascript and jQuery i suggest you learn it, it ain't hard at all. http://jquery.com/
You asking Something which is not Possible by Simple HTML.
In Addition Of HTML Code you should use JavaScript.
I suggest you to Start learning Javascript.
here is the Link. http://www.tutorialspoint.com/javascript/
Lean it.. Implement it. You will reach your Goal.
All The Best..!!