Reputation: 4612
I have several instances of the following HTML on a page:
<div class="input radio optional">
<label class="collection_radio" for="warranty_selected_environments_attributes_1__destroy_false">
<input checked="checked" class="radio optional" id="warranty_selected_environments_attributes_1__destroy_false" name="warranty[selected_environments_attributes][1][_destroy]" type="radio" value="false" />Yes
</label>
<label class="collection_radio" for="warranty_selected_environments_attributes_1__destroy_true">
<input checked="checked" class="radio optional" id="warranty_selected_environments_attributes_1__destroy_true" name="warranty[selected_environments_attributes][1][_destroy]" type="radio" value="true" />No
</label>
</div>
<div class="input numeric integer required">
<label class="integer required" for="warranty_selected_environments_attributes_1_distance">Distance</label>
<input class="numeric integer required" id="warranty_selected_environments_attributes_1_distance" name="warranty[selected_environments_attributes][1][distance]" required="required" size="50" step="1" type="number" />
</div>
This code is generated with the simple_form gem so I don't have a lot of control over it. It's also a nested attributes form so there is one of the above sets of code for each 'environment' in the system. I want to be able to show and hide the text input 'distance' depending on whether the radio group is either true or false.
I'm stuck at trying to figure out a way to watch a radio group and then know which 'distance' box on the page to hide or show. The best I can think of at this stage is to use the name value, strip off the last [_destroy] part and add [distance]. It's worth noting that all of the above is wrapped in a div per environment listed.
Apologies for the lengthy HTML :)
Upvotes: 1
Views: 1654
Reputation: 4612
Wow, easier than I thought. The handy closest() method in jquery makes this easy:
$(":radio").change(function () {
$(this).closest('.section').children('.input.numeric').toggle(this.checked && this.value == 'false');
});
Upvotes: 2