Reputation: 1710
How can I show my form content based on which radio button I have checked? Currently I have something like this:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$('.fee').show();
} else if(selected == 'false') {
$('.fee').hide();
}
});
var prev = $(".subscription_button:checked");
$(".subscription_button").change(function() {
if(confirm('really?'))
{
prev = $(this);
}
else{
prev.prop('checked','checked');
}
});
views:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<table>
<tr>
<td>
Seller Fee?
</td>
<td>
<%= radio_button("seller", "need_fee", "true", class: "subscription_button") %>
<%= radio_button("seller", "need_fee", "false") %>
</td>
</tr>
<tr class="fee" style="display:none;">
<td>Set fee</td>
<td><%= f.number_field :fee %></td>
</tr>
</table>
<%= f.submit "Save" %>
<% end %>
It is actually working when I change radio button from false to true, but what I want is that when by default button true is checked, the class "fee" is being displayed, and if by default the button false is checked, the class "fee" will display none. Thanks.
Upvotes: 0
Views: 172
Reputation: 1055
Try change this line:
<tr class="fee" style="display:none;">
To this:
<tr class="fee" style="<%= 'display:none' unless f.object.need_fee %>">
Hope this help. :)
Upvotes: 1
Reputation: 3149
Create a function for this:
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$('.fee').show();
} else if(selected == 'false') {
$('.fee').hide();
}
then call it both on DOM load and on radio-button change.
Upvotes: 0
Reputation: 24648
All you need is to trigger the change
event on the checked
button at DOM ready like so:
$('input[type="radio"]').change(function() {
//your working code
})
.filter(':checked').change(); //<<<<--- ADD THIS
Upvotes: 1
Reputation: 1891
Add a load (or ready) event:
$('input[type="radio"]').load(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$('.fee').show();
} else if(selected == 'false') {
$('.fee').hide();
}
});
Upvotes: 0