-3

I have many check-boxes on a page which appear like this, I don't know what the value is of these check boxes and as a result I don't know what the ID is:

<input value="78" type="radio" name="radio_tax_input[unit-type][]" id="in-unit-type-78">
<input value="90" type="radio" name="radio_tax_input[unit-type][]" id="in-unit-type-90">
<input value="3" type="radio" name="radio_tax_input[unit-type][]" id="in-unit-type-3">

I do know the names of the check-boxes though. I'm attempting to check if any number of these check-boxes have been checked, using jQuery:

var selected_type = $("[name='radio_tax_input[unit-type][]']:checked").length; // count the unit type selections

if(selected_type == 0){
    alert('denied');
    return false;
}

However my variable selected_type is always set to 0. Could anyone suggest why?

Liam Fell
  • 1,308
  • 3
  • 21
  • 39

3 Answers3

1
var selected_type = $('input[name="radio_tax_input[unit-type][]"]:checked').length;

This works just fine. JsFiddle: https://jsfiddle.net/sfaw9vvt/

Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
1

Try this:-

$(document).ready(function () {
    var selected_type = $("[name*='radio_tax']:checked").length; // count the unit type selections

                if (selected_type == 0) {
                    alert('denied');

                }
 });

Make sure your code is inside $(document).ready if you are not using any function

Hope this will help.

Sharique Ansari
  • 1,458
  • 1
  • 12
  • 22
  • @Liam your code is also fine make sure your code is inside `$(document).ready` if it is not inside a `function` or you have added jquery reference – Sharique Ansari May 13 '16 at 11:53
1

If you are able to surround the checkboxes with a <div> then the following will work:

var checkboxes = $('#container').find('input');
var checked = false;
for(var x = 0; x < checkboxes.length; x++){
    var box = checkboxes[x];
    if(box.checked){
        checked = true;
    }
}
if(!checked){
    alert('denied');
    return false;
}

Working: https://jsfiddle.net/ojcv14v1/1/#&togetherjs=zSaKxCDtqI

Dan Kerby
  • 55
  • 4