Reputation: 2650
I am trying to check if a set of radio buttons has been selected. However, it seems that it does not update if a radio is selected after the fact.
The code:
$('button#submit').click(function() {
var addr_chkd = 0;
$('input:radio[name="address"]').each(function() {
if (!$(this).attr('checked'))
addr_chkd++
});
});
if (addr_chkd)
// do something
When the button is clicked and nothing is selected, the code works great. However, when a radio button is selected and the button is clicked, addr_chkd
still returns a value greater than zero.
[UPDATE]
The issue is that I'm checking for addr_chkd
greater than zero. I should be checking if addr_chkd
is equal to the length of the radio buttons. I made a slight modification to @PPvG's answer and it did the trick.
$('button#submit').click(function() {
var radios = $('input:radio[name="address"]');
var num_unchecked = radios.filter(':not(:checked)').length;
if (num_unchecked === radios.length) {
alert('please select a button');
}
});
Upvotes: 0
Views: 244
Reputation: 7011
I'm not entirely clear on what you're trying to do, but I can interpret addr_chkd
in two ways.
If the "addr" stands for "adder", and you want to count the number of unchecked radio buttons, use this:
$('button#submit').click(function() {
var radios = $('input:radio[name="address"]');
var num_unchecked = radios.filter(':not(:checked)').length;
if (num_unchecked) {
// do something
}
});
If, on the other hand, "addr" means "address", and you want the index of the selected radio button, use this:
$('button#submit').click(function() {
var radios = $('input:radio[name="address"]');
var checked = radios.filter(':not(:checked)').get(0);
if (checked.length > 0) {
var index_checked = radios.index(checked);
// do something
}
});
Note that in both cases, I moved the if
clause inside the click
handler. In your example, it was outside the click
handler, which means it would be executed only once, and even before the button was clicked.
Upvotes: 2
Reputation: 18568
try this
$('button#submit').click(function() {
var addr_chkd = 0;
$('input:radio:[name="address"]').each(function() {
if (!$(this).is(':checked'))
addr_chkd++
});
});
or you can simply do it as
$('button#submit').click(function() {
var addr_chkd = $('input:radio[name="address"]:not(:checked)').length
}
since at a time only one radio button can be checked so you can also do as
$('button#submit').click(function() {
var addr_chkd = $('input:radio[name="address"]').length - 1;
}
fiddle example for all the above : http://jsfiddle.net/pdm2F/
Upvotes: 2
Reputation: 160833
You can use a much easy way:
var addr_chkd = $('input:radio[name="address"]:checked').length;
Or if you mean not checked:
var addr_chkd = $('input:radio[name="address"]').not(':checked').length;
But for the radio input, you may do something wrong.
Upvotes: 1