0

Can we make select option html input required without touching html tags by using css/javascript code?

<form action="?" method="post">
    <select class='css-class'>
        <option value=''>choose</option>
        <option value='1' data-key='1'>one</option>
        <option value='2' data-key='2'>two</option>   
        <input type="submit"/>
    </select>
</form>

css

.css-class select option{
    /* anything here to make it required */
}

I don't mind using javascript

jsfiddle

Elyor
  • 5,396
  • 8
  • 48
  • 76

2 Answers2

1

You can use JS by using the required property. It's just like the required attribute that's on tags, but it's a JS property instead of a HTML attribute.

I added another <select> to demonstrate. Try submitting only the second <select> and you'll see it'll require <select class="css-class"> to be submitted.


document.querySelector('.css-class').required = true;
<form action="?" method="post">
  <select class='css-class'>
    <option value=''>choose</option>
    <option value='1' data-key='1'>one</option>
    <option value='2' data-key='2'>two</option>
    <input type="submit" />
  </select>

  <select class='css-id'>
    <option value=''>choose</option>
    <option value='1' data-key='1'>one</option>
    <option value='2' data-key='2'>two</option>
    <input type="submit" />
  </select>
</form>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

I don't think that it is possible with just css as this is just for styling content.

Could this answer provide a solution for you: Can I apply the required attribute to <select> fields in HTML5?

The markup they suggest:

<select required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
Community
  • 1
  • 1
Sam Willis
  • 4,001
  • 7
  • 40
  • 59