0
<div class="aa">
  <input type='radio' id="1" name='choices' value='1'/>
  <input type='radio' id ="2" name='choices' value='2'/>

  <input type='radio' id="3" name='choices1' value='3'/>
  <input type='radio' id="4" name='choices1' value='4'/>
</div>

jQuery

$(".aa :radio").change(function() {

  var names = {};
  $('.aa :radio').each(function() { // find unique names
    names[$(this).attr('name')] = true;
  });
  var count = 0;
  $.each(names, function() { // then count them
    count++;
  });
  alert ("count " + count +  " length " + names.length); //names length comes up as undefined why?
}).change();
kal
  • 28,545
  • 49
  • 129
  • 149
  • 3
    Javascript objects do not have a length property: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array – Joseph Silber Aug 31 '11 at 00:09

2 Answers2

4

Because names is an object not an array. In your example, count would be the length of the keys in the object names.

To get the length of the keys:

var count = 0;
for(var i in names) {
  count++;
} 
count; // length

Or modern browsers Object.keys(names).length

Joe
  • 80,724
  • 18
  • 127
  • 145
0

Javascript objects do not have a length property. Only array's do.

If you want to know how many keys are in your object, you'll have to loop through it. Check out the answer to this question:

Length of a JavaScript object

Community
  • 1
  • 1
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292