Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

When a user selects a radio button, its ID is used to access a javascript array via jQuery's .change() function, and then a $.each function to loop through the contents and unhide form controls. However, when I run this code I get:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in programmer

**Other solutions on stackoverflow that mention this error seem to reference JSON objects, not just normal javascript arrays. I did get this code to work by incorporating an IF statement asking if the variable is "programmer" and then executing code based on that. This is not efficient in my opinion, but it did allow me to then use the actual word "programmer" instead of the dynamic variable name "position" (which would contain programmer).

Radio buttons

<label for="position">Position</label>

Programmer
...

The array:

var programmer = [  
    "blah1", 
    "blah2", 
    "blah3"
];

.change() code

$(".positionRadios").change(function() {
    var position = $(this).attr('id'); 
    if (position != null) { 
        $.each(position, function (index, value) {
            $("#" + value).show();
        });
    } else {
        $('.system').hide();
    }
});

When I tried this with a for loop, it just looped through each letter of the id string. It is not associating the string with the variable array name.

Solutions?

share|improve this question
3  
not sure what you want to do but you are using a .each with a string id (position) –  juvian Aug 6 at 17:56
    
Possible Duplicate: stackoverflow.com/questions/30269461/… –  dannypaz Aug 6 at 17:58
    
"$.each function to loop through the contents and unhide form controls" loop through what contents? –  nurdyguy Aug 6 at 18:00
    
$.each function would loop through the array's contents. So in this case it should loop through "blah1", "blah2", etc. –  user2305363 Aug 6 at 19:01

1 Answer 1

Everything I found online cited the use of parsing JSON to get the variable string to be seen as an object. In this post, I found that the use of eval(), although discouraged, actually rendered the string as an object/array. The code works now without errors. I will continue to research the JSON option.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.