OlegGerasimenko
OlegGerasimenko

Reputation: 41

How to check that radiobuttons checked on the page after click on submit button?

Please, help with this situation: I have page with radiobuttons:

<label>Delivery type:</label>
<input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7"  onclick=""><label class="label" for="del-type-7">From our office</label>
<input type="radio" name="delivery" value="6" class="delivery-item" id="del-type-6" onclick=""><label class="label" for="del-type-6">Mail Service</label>
<input type="radio" name="delivery" value="5" class="delivery-item" id="del-type-5" onclick=""><label class="label" for="del-type-5">AIR MAIL</label>
<input type="button" value="Submit order" id="order-button">

How can I checked by jquery if any radiobutton is checked after pressing submit button? And if they are not, then make the alert window with text: "Please, choose delivery type". Thank you for helping!

Upvotes: 1

Views: 53

Answers (3)

TribalChief
TribalChief

Reputation: 785

Here's an example that works without you having to specify code for each input:

$('#order-button').click(function() {
    var elementCount = $('.delivery-item').length;
    var temporaryInteger = 0;
    $(".delivery-item").each(function(){
        if(!($(this).is(':checked'))){
            temporaryInteger++;
        } 
    });
    if(temporaryInteger === elementCount){
        alert("Please, choose delivery type");
    }
});

The code above loops through each element with the class delivery-item and manipulates a variable to determine whether the alert will display.

Sample JSFIDDLE: http://jsfiddle.net/L45v9/

EDIT: This code is far less elegant compared to those of the other answerers. Use theirs!

Upvotes: 1

Kiran
Kiran

Reputation: 20313

Use jquery .is()/.prop() and :checked selector.Try this:

$('#order-button').click(function() {
    if (!$('.delivery-item').is(':checked')) {
        alert('Please choose delivery type');
    }
});

DEMO

or

$('#order-button').click(function() {
        if (!$('.delivery-item').prop(':checked')) {
            alert('Please choose delivery type');
        }
});

DEMO

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use the :checked selector, and test the length. If it's 0, there are no selected radio buttons:

$('#order-button').click(function() {
    if (!$('.delivery-item:checked').length) {
        alert('Please, choose delivery type...');
    }
});

Example Fiddle

Upvotes: 0

Related Questions