最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the "ID" of the selected value with material-ui autocomplete - Stack Overflow

programmeradmin0浏览0评论

I'm using the autocomplete component with material-ui.

  1. The data in "customerList" in the search field is no problem. But I can't get the "ID" number of the data I selected. I want to get the ID number of the selected data.

  2. Also, an error like below appears. How can I fix this?

import Autocomplete from '@material-ui/lab/Autocomplete';


class AppointmentFormContainerBasic extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  render() {

    const textEditorProps = (field) => ({
      variant: 'outlined',
      onChange: ({ target: change }) => this.changeAppointment({
        field: [field], changes: change.value
      }),
      value: displayAppointmentData[field] || '',
      className: classes.textField
    });

    const customerList = [
      {id: "1", customerName: 'John', customerSurname: "test0"},
      {id: "2", customerName: 'Bob', customerSurname: "test1"},
      {id: "3", customerNametle: 'steve', customerSurname: "test2"},
      {id: "4", customerName: 'steve', customerSurname: "test3"},
      {id: "4", customerName: 'natalia', customerSurname: "test4"}
    ];

    return (
      <AppointmentForm.Overlay
        visible={visible}
        target={target}
        fullSize
        onHide={onHide}>
        <div>
          <div className={classes.content}>
            <div className={classes.wrapper}>
              <Create className={classes.icon} color="action" />
              <Autocomplete
                id="free-solo-demo"
                freeSolo
                options={customerList.map( (option) => {
                  if (top100Films.customerName === undefined) {
                    console.log("undefined")
                  } else {
                    console.log("option.customerName")
                  }
                  return option.customerName + " " + option.customerSurname;
                })}

                
                defaultValue={displayAppointmentData['customerName']}
                onInputChange={(event, newInputValue) => {
                  this.changeAppointment({
                    field: ['customerName'], changes: newInputValue,
                    value: displayAppointmentData[newInputValue] || '',
                  });
                }}

              />
            </div>

        </div>
      </AppointmentForm.Overlay>
    );
  }
}

I'm using the autocomplete component with material-ui.

  1. The data in "customerList" in the search field is no problem. But I can't get the "ID" number of the data I selected. I want to get the ID number of the selected data.

  2. Also, an error like below appears. How can I fix this?

import Autocomplete from '@material-ui/lab/Autocomplete';


class AppointmentFormContainerBasic extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  render() {

    const textEditorProps = (field) => ({
      variant: 'outlined',
      onChange: ({ target: change }) => this.changeAppointment({
        field: [field], changes: change.value
      }),
      value: displayAppointmentData[field] || '',
      className: classes.textField
    });

    const customerList = [
      {id: "1", customerName: 'John', customerSurname: "test0"},
      {id: "2", customerName: 'Bob', customerSurname: "test1"},
      {id: "3", customerNametle: 'steve', customerSurname: "test2"},
      {id: "4", customerName: 'steve', customerSurname: "test3"},
      {id: "4", customerName: 'natalia', customerSurname: "test4"}
    ];

    return (
      <AppointmentForm.Overlay
        visible={visible}
        target={target}
        fullSize
        onHide={onHide}>
        <div>
          <div className={classes.content}>
            <div className={classes.wrapper}>
              <Create className={classes.icon} color="action" />
              <Autocomplete
                id="free-solo-demo"
                freeSolo
                options={customerList.map( (option) => {
                  if (top100Films.customerName === undefined) {
                    console.log("undefined")
                  } else {
                    console.log("option.customerName")
                  }
                  return option.customerName + " " + option.customerSurname;
                })}

                
                defaultValue={displayAppointmentData['customerName']}
                onInputChange={(event, newInputValue) => {
                  this.changeAppointment({
                    field: ['customerName'], changes: newInputValue,
                    value: displayAppointmentData[newInputValue] || '',
                  });
                }}

              />
            </div>

        </div>
      </AppointmentForm.Overlay>
    );
  }
}
Share Improve this question edited Jan 9, 2023 at 7:06 Dan Bonachea 2,4775 gold badges18 silver badges34 bronze badges asked Jul 6, 2020 at 18:41 doktorcuk fatihdoktorcuk fatih 1051 gold badge1 silver badge4 bronze badges 1
  • Any luck on this? I'm also facing the same issue. Need to get the Id of the object. Not the display value. – Thanushka Commented Dec 2, 2020 at 17:27
Add a comment  | 

2 Answers 2

Reset to default 14

EDIT As you can see from the following sample the newValue param of onChange method returns an object.

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
      onChange={(event, newValue) => {
        console.log(JSON.stringify(newValue, null, ' '));
      }}
    />
  );
}

const top100Films = [
  { id: 0, title: "The Shawshank Redemption", year: 1994 },
  { id: 1, title: "The Godfather", year: 1972 },
  { id: 2, title: "The Godfather: Part II", year: 1974 },
  { id: 3, title: "The Dark Knight", year: 2008 },
  { id: 4, title: "12 Angry Men", year: 1957 }
];

Unfortunately your code is just a fragment and it hard to determine why it does not work in your case.

I had the same issue when selecting from objects using freeSolo with Autocomplete. Neither onChange nor onInputChange returns the object from options, only the label. Without freeSolo that works.

I resorted to going through my options to find the one that matches. Then I return that to the component using SourceSelect. It is not pretty, but it works. This is my code, it is TypeScript, but the "solution" will work for JavaScript as well.

import React, {ChangeEvent} from "react";
import {Autocomplete} from "@material-ui/lab";
import {TextField} from "@material-ui/core";

type SourceSelectParams =
    {
     updateSource:(source:Source)=> void
     sourceOptions:Source[]
     preSelected:Source
    }

export default function SourceSelect(props:SourceSelectParams){

        function optionForLabel(label:string):Source{
            let toReturn = props.sourceOptions.find(
                            (source:Source)=>{ return source.name === label}
)
            if(toReturn){
                return toReturn
            }
            return {name:label}
        }

        function update(event:ChangeEvent<{}>, value:Source|string|null) {
            if(value === null){
                return
            }else if( typeof value === 'string'){
                props.updateSource(optionForLabel(value))
            }else{
                props.updateSource( value)
            }
        }


        return(<Autocomplete  options={props.sourceOptions}
                              value={props.preSelected}
                              getOptionLabel={(option) => option.name}
                              onInputChange={update}
                              onChange={update}
                              renderInput={
                                  (params) => <TextField {...params}
                                                                  label="Source"
                                                                  variant="outlined"

                              />}
                              freeSolo
                              autoSelect
                              id={'source'}/>)
}
发布评论

评论列表(0)

  1. 暂无评论