Tips on hiding the checkbox within the Material UI TextField input when using MenuItems with checkboxes

I've customized the MenuItems in a TextField of type Select to include checkboxes. However, when I select an item from the menu, the checkbox is also displayed in the input field of the TextField.

Requirement: I want to hide the checkbox in the TextField input and only use the TextField with the Select attribute.

Could someone provide assistance with this? Thank you.

https://i.sstatic.net/p3Bnr.png

sandbox link: https://codesandbox.io/s/basicselect-material-demo-forked-06gns?file=/demo.js

code:

import * as React from "react";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import ListItemText from "@mui/material/ListItemText";
import Checkbox from "@mui/material/Checkbox";
import TextField from "@mui/material/TextField";

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250
     }
  }
};

const names = ["Oliver Hansen", "Van Henry"];

export default function MultipleSelectCheckmarks() {
  const [personName, setPersonName] = React.useState([]);

   const handleChange = (event) => {
   const {
      target: { value }
    } = event;
    setPersonName(
     // On autofill we get a the stringified value.
      typeof value === "string" ? value.split(",") : value
    );
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <TextField
          // multiple
          select
          value={personName}
          onChange={handleChange}
          renderValue={(selected) => selected.join(", ")}
          MenuProps={MenuProps}
        >
          {names.map((name) => (
            <MenuItem key={name} value={name}>
              <Checkbox checked={personName.indexOf(name) > -1} />
              <ListItemText primary={name} />
            </MenuItem>
          ))}
        </TextField>
      </FormControl>
    </div>
  );
}

Answer №1

I attempted to make some adjustments to the code by moving onchange and renderValue as props on select instead of textfield, which resolved the issue.


import * as React from "react";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import TextField from "@mui/material/TextField";

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;

const names = ["Oliver Hansen", "Van Henry"];

export default function MultipleSelectCheckmarks() {
  const [personName, setPersonName] = React.useState([]);

  const handleChange = (event) => {
    if (!personName.includes(event.target.value))
      setPersonName(event.target.value); // selected options
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <TextField
          select
          SelectProps={{
            multiple: true,
            value: personName,
            onChange: (e) => handleChange(e),
            renderValue: (selected) => selected.join(", "),
            style: {
              width: "250px",
              maxHeight: `${ITEM_HEIGHT} * 4.5 + ${ITEM_PADDING_TOP}`
            }
          }}
        >
          {names.map((name) => (
            <MenuItem key={name} value={name}>
              <FormControlLabel
                control={<Checkbox checked={personName.includes(name)} />}
                label={name}
              />
            </MenuItem>
          ))}
        </TextField>
      </FormControl>
    </div>
  );
}

To see a working demo, click here: https://codesandbox.io/s/multi-select-with-textfield-uf100

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

Can somebody please tell me the equivalent of the sleep() function in JavaScript?

Are there more efficient ways to implement a sleep function in JavaScript compared to the pausecomp function as shown below (sourced from here)? function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); ...

Steps to activate the parent list item when the child item is altered

As a newcomer to both ui router and angularjs, I'm encountering a specific issue: Within my header section, the following code is present: <li ng-class="{active: $state.includes('settings')}" id="header01"> <a ...

Ways to eliminate the margin space on a Bootstrap 4 progress bar

Currently experimenting with the Bootstrap 4 Progress component and attempting to integrate it within a sentence. Customizing its width to fit between words while realizing it is usually meant to occupy an entire row. Despite reducing its size, there seems ...

Transmitting boolean values from a Python API request

Is it possible that the error in my script is due to the boolean value I am trying to send in an API put call using Requests in Python? Here is how my script looks: import requests data = { 'name': 'John', 'lastname': ...

What is the best way to refresh an SPFx web part after a post request?

As I develop an spfx webpart using the React framework, I have encountered an issue with reloading. In my render method, I have various controls such as a button and checkboxes that send data to SharePoint via a post method (this.context.spHttpClient.pos ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

What is the solution to the error message: "Expected a function for the onChange listener, but received a string value instead in the @uiw/react-md-editor for NextJS 13"?

In my Next.js 13 application, I have integrated @uiw/react-md-editor as a markdown editor. One of its features is the ability to preview markdown using MDEditor.Markdown. However, I encountered an error that stated: Warning: Expected onChange listener to ...

Learn the steps for assigning a distribution tag to an npm package within a private registry

Operating with my own exclusive Gemfury repository, I am actively releasing npm packages. Intrigued by the prospect of applying distribution tags to my packages (as per this guide: https://docs.npmjs.com/cli/dist-tag). The configuration of my npm registr ...

Button and input elements within Popover HTML content failing to display

I'm attempting to include a button in a popover, but for some reason, it's not showing up. Is the way I've set it up correct or is there a more effective method? $('#myinput').popover({ trigger : "focus", container : ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

The issue of 'position: fixed' not properly functioning within the Materialize CSS modal

My goal is to have the header of the Modal stay fixed while scrolling, but for some reason, the option position:fixed; is not working. I am currently using Materialize CSS to build the modal and surprisingly, position:sticky; is working. $(document).rea ...

What is the method of updating content on a webpage without altering the page itself or using hashed URLs?

I have a good understanding of how to update webpage content through AJAX and loading remote content. However, I recently came across UStream's innovative new layout. When you click on any video, not only does the content change seamlessly without rel ...

Is there a way to create a button that directs to a different page, while also automatically populating a search bar with specific information?

Here we have a bootstrap dropdown menu that features various product categories. Each button should lead to a Product.html page where an Angular JS search bar is utilized. The goal is for the search bar to be pre-filled with the name of the selected button ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

Bottom is not adhering properly to the page (blocking content)

Hey there! I'm using Weebly as a CMS for my website, and I've encountered some issues with a custom footer. Specifically, on this page: The content seems to disappear if you're not using a large monitor and the page height is short. Upon in ...

How to Trigger a Javascript Function from an OnItemClick Event in ASP.NET ListView

In order to achieve the functionality of refreshing ListView No.2 without refreshing the entire page when a user clicks on an item in ListView No.1, I am attempting to use JavaScript. Here is what I have tried so far: ListView No.1: <asp:ListView ID=" ...

Creating unique jQuery objects by comparing specific object properties

I am looking to create an array of unique objects by removing duplicate objects with specific property values. For example, consider the following code snippet where event1 and event2 have identical titles and start values, while event3 and event4 share th ...

"Customized Bootstrap button featuring a tooltip and modal, experiencing incorrect padding within the button group design

I encountered an issue with a button-group containing 2 buttons, each with a tooltip and a modal. Bootstrap recommends wrapping the buttons with spans to manage two "data-bs-toggle" attributes, which is what I initially did. While the functionality works ...

Maximizing efficiency in website reloading and development with Sinatra using Ruby along with Rack and Haml

In my efforts to build a Sinatra website, I have gone from using Shotgun to now utilizing Rerun for reloading my Thin server whenever I make file edits. However, the development cycle is proving to be quite time-consuming. Even small changes to CSS, JavaS ...

The Angular Material Datepicker lacks any selected date

I am currently in the process of developing a web application using Angular and incorporating Angular Material for certain UI components. I have encountered an issue that I am unable to resolve. When attempting to use the datepicker as outlined on https:// ...