React JS: Pass event inside onChange drop down (Ant Design) - javascript

I have a drop down in my form (https://ant.design/components/select). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event.
Here is the code:
export default class MyForm extends Component {
constructor() {
super();
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
console.log(event); // here I'm receiving only the value selected (1 or 2)
}
render() {
render(
<Form>
<Select onChange={this.handleOnChange}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
}
In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()?

I found a solution. Just use: onSelect(), passing the value and the event.
handleOnChange = (value, event) => {
...code here
}
render() {
render(
<Form>
<Select onSelect={(value, event) => this.handleOnChange(value, event)}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}

The Select component that you use is the one that handle the onChange and call your "outer" function.
What you can try is use the synthetic event variable inside your function, it might work:
handleOnChange = (selectedValue) => {
console.log(selectedValue); // The value from the inner component
console.log(event); // usually you have access to this variable
}

Try this, if you dont want to bind in callback in Select onSelect/onChange:
toggleActive = name => event => {
console.log("name: ",name) // prints "name: Active!"
console.log("event: ",event) // event is some data
}
<Select
mode="multiple"
style={{ width: '91%' }}
placeholder="Stuff"
value={this.props.value}
onChange={this.toggleActive("Active!")}
>

Related

How to perform an operation with an undefined amount of <select>?

I have the following code in html:
<select onchenge="action('account1')">
<option value="1">op 1</option>
</select>
I need the function to also receive the selected value without using an id. (because I have an unlimited amount from the tag)
How can this be done?
This is my javascript code:
function action(account) {
const email = account
const select = // value*
}
Your onChange listener to be a function, instead you put a string. It should be something like the below code. Hope this will help you.
export default function App() {
....
function action(e, account) {
....
const select = e.target.value;
}
return(
....
<select onChange={(e) => action(e, "account1")}>
<option value="1">op 1</option>
</select>
....
)
}

Uncaught Reference Error xyz is not defined when trying to pass parameters

I am currently trying to pass parameters to set the state of the current size selected depending on which option the user is currently on, so i setup a function as well as a parameter that whenever onSelect is triggered it passes the variable of the size but for some reason im getting that my function is not defined, im guessing its my syntax but i cant seem to figure it out, here is my current code:
const updateSize = userSize = () => {
setSize(userSize);
console.log(userSize);
}
<select className="buttons form-control mb-2">
<option onSelect={updateSize("Small")}>Small</option>
<option onSelect={updateSize("Medium")}>Medium</option>
<option onSelect={updateSize("Large")}>Large</option>
</select>
Instead of const updateSize = userSize = () => { make it const updateSize = (userSize) => {
Instead of setting event listeners on individual options, set it on the <select> tag itself. Then get the text of the option selected and use it in tour code.
HTML
<select onchange="updateSize()" className="buttons form-control mb-2" id="select">
<option>Small</option>
<option>Medium</option>
<option>Large</option>
</select>
JS
<script>
function updateSize() {
let select = document.getElementById('select');
let text = select.options[select.selectedIndex].text;
console.log(text)
}
</script>
Text value can be Small, Medium or Large depending on what option was selected.
Issue was because my function was inside another function without me noticing thus outside the scope.
If you want to give parameter to a const function use below method.
<select className="buttons form-control mb-2">
<option onSelect={()=>updateSize("Small")}>Small</option>
<option onSelect={()=>updateSize("Medium")}>Medium</option>
<option onSelect={()=>updateSize("Large")}>Large</option>
</select>
Also for your updateSize function. keep the parameters inside the ().
const updateSize = (userSize) => {
setSize(userSize);
console.log(userSize);
}

Handling events on dynamically created <select> dropdown options

Let's say I have a function which returns a dropdown. This function gets called from some parent, where the parent passes in props including a state key, array, and onChange. The dropdown is created dynamically from the items in the array. What I want to happen is, when an option in the dropdown is selected, the parents passed in state key gets updated to the value of whatever was selected. Currently, I am trying to do this by setting an onClick handler per , which doesn't work. Instead, I am met with either no or undefined values (described more below).
Example flow:
Parent passes in aStateKey (actual state key), an array to be used as dropdown values, and an onChange function to be used to update aStateKey
The dropdown menu is created from the passed inarray
A dropdown item is selected
aStateKey (which was passed in as a prop) gets updated via the passed in onChange function.
I understand that the traditional method is to give and onChange handler, but I am having troubles working out how to get the desired described above.
Parent
state = { aStateKey: "" };
someArray = ["test", "another test"];
updateField = (name, value) => {
console.log("Updating field: " + name + " with value: " + value);
}
return(
<div>
<CreateDropdown name="aStateKey" items={this.someArray} onChange={this.updateField} />
</div>
);
CreateDropdown
function CreateDropdown(props) {
const handleClick = event => {
console.log("changed name:" + event.name + "changed value: " + event.value);
props.onChange(event.name, event.value);
};
return (
<div>
<select>
{props.items.map(field => (
<option key={field} value={field} name={props.name} onClick={handleClick}>
{field}
</option>
))}
</select>
</div>
);
}
Console log
Shows nothing! However, if I move the onClick from <option> to <select>, i.e.
return (
<div>
<select onChange={handleClick}>
{props.items.map(field => (
<option key={field} value={field} name={props.name}>
{field}
</option>
))}
</select>
</div>
);
The console shows:
Updating field: undefined with value: undefined.
changed name:undefinedchanged value: undefined
How can I achieve my desired behavior?
your target form this event is select and use onChange and here the updated function you need:
function CreateDropdown(props) {
return (
<div>
<select name={props.name} onChange={e =>
props.onChange(e.target.name, e.target.value);}>
{props.items.map(field => (
<option key={field} value={field}
{field}
</option>
))}
</select>
</div>
);
}
UPDATE #1
Inside handleClick, you are using event.name and event.value to get the target values you want.
instead use event.target.name and event.target.value
Try using onChange instead of onClick in your select element.
It belongs to select not option elements.

React submit form on select change event

I'm using ant design. I have a form. In that form I have submit button and select dropdown.
when I click submit button it triggers the form submit action.
I need to submit form and get values on select change event.
Code sandbox: https://codesandbox.io/s/xrpzw7wn8q
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log("Received values of form: ", values);
}
});
};
I will try to answer this question in a more general way because it pops in the search results and it may help some people.
To submit a select form on a change event (without a submit button) in React, you have to do two things:
use the "onChange" property to fire a function to send the value.
in this function, you have to trigger the submit action of the form.
To do number 2, in classical javascript you would grab a reference to the form and then use the submit() method. In React, to grab the form, you can use "useRef". The submit() method is then accessible on the "current" property. Here is an implementation:
import { useRef }, React from "react"
export default function SelectOnChange () {
const selectForm = useRef(null)
const handleSubmit = () => {selectForm.current.submit()}
return (
<form ref={selectForm} method="get" onChange={handleSubmit}>
<select name="sort" id="sort">
<option value="relevance">Relevance</option>
<option value="score">Score</option>
</select>
</form>
)
}
You can add a callback to the onchange event of the Ant Design Select component, that could handle the form submit:
<Select
allowClear
onChange={
(value) => {
// your code to submit the form
}
}
>
<Option key={1} value={1}>
something 1
</Option>
<Option key={2} value={2}>
something 2
</Option>
</Select>
BUT from an UX perspective, if the submit button has to be present, it should be it to trigger submitting
You can do something along those lines:
<Select allowClear onSelect={ (val, event) => this.handleSubmit(event) }>
Add the onChange() or onSelect() from ant design select and access the values from the form in the callbacks.
state={
selectValue : "default value",
otherFormItemValue: "default other value"
}
handleSubmit = () => {
serviceCallToSubmitForm(this.state.selectValue, this.state.otherFormItemValue);
}
//In the render() of component
<Select
onChange={
//or onSelect
(value) => {
this.setState({selectValue: value});
this.handleSubmit()
}
}
>
<Option key={1} value={"value 1"}>
something 1
</Option>
<Option key={2} value={"value 2"}>
something 2
</Option>
</Select>
<Button onClick={this.handleSubmit}>Submit</Button>
Hope this helps and is clear enough.
The handleSubmit function is used to access the form values from the state and submit it.
The onChange function call it used to :
1. Store the dropdown value in the state
2. call the handleSubmit function to actually submit in the same action [not recommended UX-wise]
Here is code sandbox.
https://codesandbox.io/s/r00v7x8r7q
Select dropdown item and check console for the respected value.
Getfield decorator doesn't have onchange option, so remove it and add onchange event to select tag instead of getfield decorator.
Check ant docs for available options.
https://ant.design/components/form/
getFieldDecorator(id, options) parameters

If option selected do something

I have form. I want to do something, if the certain option is selected. I try this
if (document.getElementById('order-select').value == "Услуга") {
alert("blabla");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="order-select">
<option value="Услуга" class="item-1">Услуга</option>
<option value="Строительный проект" class="item-2">Строительный проект</option>
</select>
Problem : I want to alert every time, when option is selected.
Need help
You need to attach an event listener for the change event.
When the event is fired, you can access the element through the target object on the event object.
document.getElementById('order-select').addEventListener('change', function (e) {
if (e.target.value === "Услуга") {
alert('Selected');
}
});
<select id="order-select">
<option class="item-1">--Select--</option>
<option value="Услуга" class="item-2">Услуга</option>
<option value="Строительный проект" class="item-3">Строительный проект</option>
</select>
Updated Example
document.getElementById('order-select').addEventListener('change', function (e) {
if (e.target.value === "Услуга") {
alert('Selected');
}
});

Categories