Home > Software engineering >  <Select> first value disabled and selected
<Select> first value disabled and selected

Time:07-16

i'm building an e-commerce site and i have a size, mapped with mongoDB, that has values ["XS","S","M","L","XL"].

The problem i got is when the user choose a product, he might see the selected size value on XS by default because it's the first value on the object list, he wont change it and press on checkout button. Then in the cart page he will see there's no size selected.

How to add a first value as selected and disabled so the user will be obligated to change the value of select and choose a value, just something like this in HTML:

<select>
   <option selected="true" disabled="disabled">Choose a size:</option>
   <option>XS</option>
   <option>S</option>
   <option>M</option>
   <option>L</option>
   <option>XL</option>
<select/>

My code:

const FilterSize = styled.select`
  margin-left: 10px;
  padding: 5px;
  cursor: pointer;
  outline: 0px;
  font-size: inherit;
`;
//...
              <Filter>
                <FilterTitle>Size</FilterTitle>
                <FilterSize onChange={(e) => setSize(e.target.value)}>
                  {product?.product?.size.map((s) => (
                    <FilterSizeOption key={s}>{s} </FilterSizeOption>
                  ))}
                </FilterSize>
              </Filter>

CodePudding user response:

You need to change the JSX to this

 <Filter>
    <FilterTitle>Size</FilterTitle>
       <FilterSize onChange={(e) => setSize(e.target.value)}>
        <FilterSizeOption selected={true} disabled="disabled" >Choose a size:</FilterSizeOption>
           {product?.product?.size.map((s) => (
             <FilterSizeOption key={s} value={s}>{s} </FilterSizeOption>
            ))}
       </FilterSize>
 </Filter>
  • Related