1

I have a form that must let user to check , but I need to alert if they click submit but didn't choose any of the radio button options.

 <label class="radio-inline"><input type="radio" name="optradio" value="Amount" >Amount</label>
 <label class="radio-inline"><input type="radio" name="optradio" value="Quantity" >Quantity</label>
 <label class="radio-inline"><input type="radio" name="optradio" value="Profit" >Profit</label> 

How can I achieve it ? Thanks.

1 Answers1

1

Most straightforward approach would be using HTML5 validation: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

Here's the example:

<form>
     <label class="radio-inline"><input type="radio" name="optradio" value="Amount" required>Amount</label>
     <label class="radio-inline"><input type="radio" name="optradio" value="Quantity"  required>Quantity</label>
     <label class="radio-inline"><input type="radio" name="optradio" value="Profit" required>Profit</label> 

    <input type="submit">
</form>

Note: Adding required property to one of the radio buttons only would work as well, but adding to each makes it more clear.

In order to have more control over how the error message is presented, you'd have to write custom validation using JS.

Edit: HTML5 validation does not on IE <= 9 (but then again, it's IE ;-)) – https://caniuse.com/#feat=form-validation. Thanks @JustCarty

Cheers.

Mladen Ilić
  • 1,667
  • 1
  • 17
  • 21
  • Thanks, that's a simple solution. –  Sep 20 '18 at 08:25
  • Glad to help, if this answer solved your problem please mark it as accepted by clicking the check mark next to the answer. see: How does accepting an answer work? for more information. – Mladen Ilić Sep 20 '18 at 08:28
  • 2
    Note, this is an HTML5 attribute and won't work in IE <= 9. See [caniuse](https://caniuse.com/#feat=form-validation). – JustCarty Sep 20 '18 at 08:34