user10103713
user10103713

Reputation:

PHP - How do I alert if no radio button is chosen?

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.

Upvotes: 1

Views: 364

Answers (1)

Mladen Ilić
Mladen Ilić

Reputation: 1765

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.

Upvotes: 1

Related Questions