gates
gates

Reputation: 4593

How to prevent a form submission if radio button is not clicked

var $form = $('#style');
    var $radio = $('.changeprice');

    $form.submit( function(e) {
        if(!$radio.is(':checked')) {
            alert('Please confirm!');
            e.preventDefault();
        }
    });     

This is the JS code I have in in document ready function.

here is the html form related code

<%= simple_form_for @order, url: wizard_path, :method => :put, id: 'style' do |f| %> 
    <input type="radio" id="1" class="changeprice"  />
    <input type="radio" id="2" class="changeprice"  />

<%end %>

Upvotes: 1

Views: 1584

Answers (1)

Jared
Jared

Reputation: 1184

Just put the HTML 5 tag of required on one of your radio buttons. Putting it on one makes it so that at least one in the set is required before submitting. No need for your JS to stop the form from being submitted without a choice.

<%= simple_form_for @order, url: wizard_path, :method => :put, id: 'style' do |f| %> 
    <input type="radio" id="1" class="changeprice" required />
    <input type="radio" id="2" class="changeprice"  />

<%end %>

Upvotes: 2

Related Questions