views:

25

answers:

1

I have a javascript array containing the name and values of radios I want checked.

jQuery(window).load(function(){

var selected_options = new Array();
selected_options['swing_type'] = 'Slide';

    var x;
    for (x in selected_options){
        jQuery("#menu input[name="+ x +"][value="+ selected_options[x] +"]").attr('checked', 'checked');
    }
});

And the html has something like:

<td>
    <input type="radio" id="swing" name="swing_type" value="Swing" /><label for="swing"> Swing</label><br />

    <input type="radio" id="slide" name="swing_type" value="Slide" /><label for="slide"> Slide</label>
  </td>

When I run this script, the browser becomes unresponsive. I've tried a few variations, the following two worked:

 jQuery("#menu input[value="+ selected_options[x] +"]").attr('checked', 'checked'); 
jQuery("#menu input[name=swing_type][value=Swing]").attr('checked', 'checked');

The following did not work:

jQuery("#menu input[name=swing_type][value="+ selected_options[x] +"]").attr('checked', 'checked');

I'm hoping someone can enlighten me to what is wrong. I want to target the correct radio inputs. If I only target the values, I could see a case where there could be two separate sets with Yes/No values. Thanks.

+2  A: 

You're doing a for/in over an Array. This can sometimes cause problems.

Since you are specifying named keys, you should use an object instead:

var selected_options = {};

or

var selected_options = new Object();

Test the example: http://jsfiddle.net/Ds3s8/

patrick dw
I'll give it a try thanks.
dardub
Wow thanks, I just changed one word and that solved the problem.
dardub
@dardub - Awesome! Glad it worked! :o)
patrick dw