MUI AutoComplete does not currently support the type number with maxLength restriction. What steps can be taken to resolve this issue?

Hey there, I'm encountering an issue where maxLength is not working on the AutoComplete component when the input type is set to number. Any suggestions on how to resolve this?

export default function Select({
    onChangeInput,
    label,
    name,
    value,
    options,
    placeholder,
    disabled,
    error,
    helpertext,
    required,
    shrink,
    maxLength,
    type
}) {

    const _onChange = useCallback((e, v) => {
        onChangeInput(v)
    })

    return (
        <Autocomplete
            freeSolo
            fullWidth={true}
            multiple={false}
            margin={'noraml'}
            readOnly={disabled}
            name={name}
            isOptionEqualToValue={useCallback((option, value) => option.label === value.label)}
            value={value}
            options={options}
            placeholder={placeholder}
            renderInput={useCallback(params => {
                return <TextField {...params}
                    type={type}
                    label={label}
                    error={error}
                    required={required}
                    helperText={helpertext}
                    variant={'standard'}
                    inputProps={{ ...params.inputProps, maxLength: (maxLength && parseInt(maxLength)) || 99}}
                    InputLabelProps={{ shrink: shrink, style: { fontSize: 18 } }}
                />
            })}
            onInputChange={_onChange}
        />
    )
}

Answer №1

Utilizing the inputProps properties of TextField Component to adjust user-provided values in the following manner:

export default function Select({
    onChangeInput,
    label,
    name,
    value,
    options,
    placeholder,
    disabled,
    error,
    helpertext,
    required,
    shrink,
    maxLength,
    type
}) {

    const _onChange = useCallback((e, v) => {
        if (maxLength && parseInt(maxLength) >= v.length) {
            onChangeInput(v)
        }
    })

    const modifiedValue = maxLength ? value?.slice(0, parseInt(maxLength)) : value

    return (
        <Autocomplete
            freeSolo
            fullWidth={true}
            multiple={false}
            margin={'normal'}
            readOnly={disabled}
            name={name}
            isOptionEqualToValue={useCallback((option, value) => option.label === value.label)}
            value={modifiedValue}
            options={options}
            placeholder={placeholder}
            renderInput={useCallback(params => {
                return <TextField {...params}
                    type={type}
                    label={label}
                    error={error}
                    required={required}
                    helperText={helpertext}
                    variant={'standard'}
                    inputProps={{ ...params.inputProps, maxLength: (maxLength && parseInt(maxLength)) || 99, value: modifiedValue}}
                    InputLabelProps={{ shrink: shrink, style: { fontSize: 18 } }}
                />
            })}
            onInputChange={_onChange}
        />
    )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

I successfully coded a function without utilizing the function key, but unfortunately I am encountering difficulties when trying to output the

I have created a function without using the function keyword. The function should take the age above 15 and push it into an array. I have been able to do that, but I am struggling to print the result. Can anyone help me with this? my code <script> ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

How can I ensure that my text input and button are in sync in ReactJS?

I'm currently developing a basic search bar that reads input and updates the 'inputString' state when the content changes. Upon clicking the 'search' button, the inputString is split and assigned to the 'keywords' state a ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Using anti-cache code in jQuery's getJson function

During an interview, I was presented with the following question: Can you provide a one-liner code showing the proper syntax to add an anti-cache code to all jQuery getJson calls in a project without individually adding it to each call? I must admit th ...

The necessary directive controller is missing from the element in the current DOM structure

Can anyone explain the meaning of "required directive controller is not present on the current DOM element"? I encountered this error and would like some clarity. For reference, here is the link to the error: https://docs.angularjs.org/error/$compile/ctr ...

Utilizing Discord.js to import a variable from a method in a separate file

I'm working with two commands: join and disconnect. The join command allows the bot to join a voice channel using the joinVoiceChannel method, while the disconnect command removes the bot from the channel by utilizing the getVoiceConnection method: ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Can JavaScript be used to bypass AJAX cookies?

Is there a way in JavaScript to programmatically ignore server-sent cookies without adjusting browser settings? We have implemented plugins on our web server that periodically update our security cookie, resulting in compatibility issues with certain URLs ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

Can a dynamic react component be inserted into a standalone HTML document without the need for file downloads or server support?

I am implementing React for a Single Page Application (SPA) project where users can customize a component's font size, color, etc., and then embed this customized component into their website. I'm looking for a way to bundle the component and pre ...

What's the reason that app.use(app.static(...)); isn't functioning properly?

As someone who is new to programming, I am currently exploring Javascript, node.js, and express. I came across a question regarding the usage of app.use(express.static(path.join(...))); versus app.use(app.static(path.join(...)));. const app = express(); co ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

Is there anything resembling 'Spread' and 'allSettled' in node with Q?

In my experience with Q, I have found the Q.allSettled function to be incredibly useful for handling arrays of promises, especially when needing to manage failure cases without using a specific fail handler. Currently, I find myself needing to utilize the ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

Is it possible for a JavaScript environment to restore function normally after modifying the [[Prototype]] of an object?

After thoroughly reviewing the MDN disclaimers and warnings, as well as an enlightening discussion in a popular online forum, I still find myself seeking answers. This question arose from a previous exchange, which can be found here. Imagine if I were to ...

There seems to be a problem with the full calendar updateEvent feature as it is unable to read the property 'clone'

Struggling to update an event using FullCalendar and a modal. Encounter the 'cannot read property 'clone' of undefined' error when attempting to update. Following the documentation, I utilize the clientEvents method. It is crucial t ...