How to access the selected option in React - javascript

In React JSX, I wrote below component:
<select //...
onChange={event => {alert(event.target); //setState}}
>
<option id=1>one</option>
<option id=2>two</option>
</select>
The alert gives me select element. How can I access selected option without jQuery? I am trying to setState on the id, and do corresponding searches and other things.

Instead of an id on select option, provide the value attribute you can then access it as event.target.value.
<select
onChange={event => {
alert(event.target.value);
}
}>
<option value="1"> one</option>
<option value="2"> two</option>
</select>
CodeSandbox

You wouldn’t typically access the value directly through the event target. Either bind the control value to component state or store a reference on the parent component... then you can access the value when the event is fired.
See: https://stackoverflow.com/a/47842562/1306026

You can access selected option like:
var elm = event.target;
console.log(elm.options[elm.selectedIndex]);
and then access its value or text like:
console.log(elm.options[elm.selectedIndex].value)
DEMO (change the option to see result):
function setState() {
var elm = event.target;
console.log(elm.options[elm.selectedIndex]);
console.log(elm.options[elm.selectedIndex].value);
}
<select onChange="setState()">
<option id=1>one</option>
<option id=2>two</option>
</select>

Related

How do I change state on dropdown select in React

for a bit of context I'm trying to make a component navigation menu for my react app. Essentially each dropdown value is equivalent to some components. The way I was going to do this is like follows:
Dropdown menu
<form>
<label htmlFor="#endpointSelect">Endpoint:</label><br/>
<select value={moduleValue} id="endpointSelect" onChange={() => activateModuleValue()}>
<option value="1"> Latest </option>
<option value="2"> Convert </option>
<option value="3"> Historical </option>
<option value="4"> Time Series </option>
<option value="5"> Fluctuation </option>
<option value="6"> Carat </option>
<option value="7"> Lowest-Highest </option>
</select>
</form>
And this is the activateModuleValue()
const [module, setModule] = useState();
// set the module value
const activateModuleValue = () => {
console.log(moduleValue);
}
Eventually there will be a method with a bunch of if statements indicating 1 = <Latest/>, 2 = <Convert/>, etc.
What I was having issues with is correctly grabbing the option values. Using onChange in general I've noticed it returns the value FROM the element I'm changing from instead of changing TO.
Another approach that I'm currently trying is using the value={moduleValue}. Essentially on dropdown select the moduleValue state should change, and ideally I'd have something along the lines of:
useEffect(() => {
activateModule();
}, [moduleValue]);
Where the intent would be to call on the "setActiveComponenet" method whenever the state for moduleValue changes
As an answer to my own question, you have to first set the state and then separately associate state with a component:
// set the module value
const activateModuleValue = (e) => {
setModuleValue(e)
}
// set the module
const activateModule = () => {
if(moduleValue == 1){
setModule(<Latest/>)
}

what is the event that needed to use for multiselect in React

I want to filter a list of movies based on their categories by selecting them using a select menu (select tag), I could do it with a button using on click event it works, but when I want to replace it buy multi-select by changing the event to onChange the filter didn't work.
what do you think?
Thank you
//filter movies based on their categories, this function is created in App.js, it has been passed as props to my CategoriesFilter components
const filterMovie = (category) => {
const filterMovie = MoviesData.filter((movie)=> movie.category === category);
setMoviesList(filterMovie);
}
// this my components
const CategoriesFilter = ({categories, filterMovie}) => {
return (
<div>
<select >
{categories.map((category, index)=> {
return (
<option key={index} onChange={()=> filterMovie(category)}>{category}</option>
)
})}
</select>
</div>
)
}
There are a few options.
You can probably build a custom multi select dropdown component with checkboxes for each item.
You can use third party npm packages like react-select. https://www.npmjs.com/package/react-select
I would suggest you to use the react-select.
You can also use select tag with multiple attribute. But it won't work the way you want it to.
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
To select multiple items, you'll have ctrl + click the items
Multiple select is <select multiple/>
onchange event is not associated with each option, it is an event of select element.

How to use computed property with getters and setters to trigger commit in Vuex

I am using a computed property: category in an input field bound by v-bind like following:
<select name="Category" :value="category">
<option value="AC">AC</option>
<option value="TV">TV</option>
...
</select>
and I have getters and setter for this computed property as follows:
computed:{
category: {
get () {
return this.$store.state.category
},
set (value) {
console.log("Value of category changed")
this.store.commit("SET_CAT", value)
}
}
}
But when I change input, setter does not get called, How can I achived this, or what other way can be to change state variable directly from HTML input field.
Here is fiddle for this.
This worked just by change v-bind to v-model in select.
<select name="Category" v-model="category">
<option value="" disabled hidden>Select Product</option>
....
Here is working fiddle.
Please post answer if you feel there is still some better way to do it.

Alternative to .change in jquery?

I'm trying to fire an ajax event, and passing the value of select list options as arguments in the ajax call. Unfortunately, I'm firing the call on the .change event, and it is passing the values of the select option before the new option has been selected (i.e passing the previously selected options values). Is there an event which will get the current values of the option selected? Much thanks in advance,
<select id='theList'>
<option> Option 1</option>
<option> Option 2</option>
</select>
In the JS:
$('#theList').change( function() {
$.getJSON('Home/MethodName', { var1: Option1Value, var2: MiscValue}, function(data) {
//Execute instructions here
}
)});
I wanted to use .trigger, but I think that fires beforehand as well.
I think .change() is what you want, but you're misusing it. The change event fires after the value has changed. In your handler, you need to read the new value:
$('#theList').change( function() {
var value = $('#theList').val();
$.getJSON('Home/MethodName', { your_key: value }, function(data) {
// ...
}
)});
You also might want to set values on your <option> tags:
<option value="something"> Option 2</option>
You must be doing something wrong when getting the current select value. The following works correctly for me.
http://jsfiddle.net/TJ2eS/
<select id="demo">
<option value=""></option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
$("#demo").change(function() {
alert("current select value " + $(this).val());
});
A word of warning, .change is now defunct, you should use...
.on('change', function()
Like that.

Get previously selected value or prevent default on select

Is it possible on <select> get previously selected value or prevent default somehow? For example i have
<select id="select_site" name="sites" selectedindex="0">
<option value="">Please select site</option>
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</select>
So if selected option with null value i need to restore previously selected second value.
You can bind a change event handler to the element and store the new value in a variable. If the value is an empty string, set it to whatever is in the variable:
$('#select_site').change(function() {
if (this.value === '') {
this.value = $(this).data('previous_value');
}
else {
$(this).data('previous_value', this.value);
}
}).triggerHandler('change'); // <- trigger change event to get initial value
DEMO
no js needed:
<select id="select_site" name="sites" selectedindex="0">
<optgroup label="Please select site">
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</optgroup>
</select>
demo: http://jsbin.com/obeker/1/
ref: https://developer.mozilla.org/docs/HTML/Element/optgroup
No you cannot do that because the change event is fired after the select is focused out, not before the selection is changed. There is no native "onbeforechange" event but you can remove the empty value once the selection is changed so it is no longer available.
Code to do this:
$('select').change(function (event) {
$this = $(this);
if ($this.val() !== '') {
$this.children('option:first').remove();
}
});

Categories

Resources