Reputation: 41
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
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
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');
}
});
or
$('#order-button').click(function() {
if (!$('.delivery-item').prop(':checked')) {
alert('Please choose delivery type');
}
});
Upvotes: 2
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...');
}
});
Upvotes: 0