Home > Mobile >  How do I put static text in a select element in html?
How do I put static text in a select element in html?

Time:12-29

I currently have a select element as follows:

<select  id="startYear" onChange={(event) => setStartYear(event.target.value)}>

Then I have a bunch of options elements as well. Each looking as follows:

<option value=2017 selected={2017 == startYear}>2017</option>
<option value=2018 selected={2018 == startYear}>2018</option>
//lots of different years continuing on

I'm hoping to make it so that there's a static text that says "Start:" and then the dropdown is just all of the years (without the text). See the image below as an example. Anyone know where I can add the "Start:" text?

Example Drop Down

CodePudding user response:

You would usually use a label for this kind of thing, where the label is to the left and the select box to the right.

div {
  border: 1px solid black;
  width: 100px;
  border-radius: 15px;
  padding: 5px 0 5px 10px
}

select {
  border: none
}
<div>
  <label for="start">Start: </label>
  <select id="start">
    <option>2017</option>
  </select>
</div>

There is still an arrow there which your example image doesn't show, however, I would argue that you want to have the arrow there to denote that it's a select box/drop down. Without it, there's no indication and it's not friendly UX.

CodePudding user response:

I was able to achieve this effect by surrounding the whole thing in a div, and adding the text and select there. With some css, it looks like a normal select prompt. You may have to fiddle with some of the variables to make it to your liking.

.select{
        display: inline-block;
        border: 2px solid black;
        border-radius: 5px;
        padding: 5px;
    }

    .select select {
        display: inline-block;
        border: none;
        background-color: transparent;
    }

    .select select:focus-visible{
        background-color: transparent;
        border: none;
        outline: none;
    }

    .select p {
        display: inline-block;
        text-align: center;
        margin: 0;
    }
<div >
    <p>Start:</p>
    <select>
        <option>15432542</option>
        <option>54326</option>
        <option>654262</option>
    </select>
</div>

  •  Tags:  
  • html
  • Related