Search code examples
htmlrequired

HTML: Required Field, need assistance


So I'm trying to make a form and I'm having trouble making it so everything is required these two no matter where I put the required field won't make them required.. Can someone explain it to me?

Select Your Room:
<select id="room" name="room">
  <option disabled selected>
        Choose a room
  </option>
    <option value="S308">
        S308
    </option>
    <option value="S324">
        S324
    </option>
    <option value="L2">
        L2
    </option>
    <option value="ME201">
        ME201
    </option>
    <option value="ME208">
        ME208
    </option>
</select>
<p>Machine Number:</p>
<!-- add label  here -->
<label for="machinenum">1 - 15</label>
<input id="machinenum" name="quantity" type="machinenum" min="1" max="15" value="1"><br>

(I'm only showing the part I don't understand. My code has <form>, etc.)


Solution

  • Below working example. Changes I made:

    • put your snippet in a form
    • added required attribute for select and input elements to enable HTML5 validation
    • added value="" for the default option to enable
    • added submit button to test the form

    Select Your Room:
    <form>
        <select id="room" name="room" required>
          <option disabled selected value="">
                Choose a room
          </option>
            <option value="S308">
                S308
            </option>
            <option value="S324">
                S324
            </option>
            <option value="L2">
                L2
            </option>
            <option value="ME201">
                ME201
            </option>
            <option value="ME208">
                ME208
            </option>
        </select>
        <p>Machine Number:</p>
        <!-- add label  here -->
        <label for="machinenum">1 - 15</label>
        <input id="machinenum" name="quantity" type="machinenum" min="1" max="15" value="1" required><br>
        <button type="submit">
        Submit
        </button>
    </form>