Reputation: 340
I would like to show/hide additional submit button depending on selected value in form.
I have no experience with JavaScript so I have only tried to modify examples found on web.
Unfortunately I couldn't find anything related with rails form_for
.
Here is what I have tried so far:
<%= form_for @discount, url: {action: "create"} do |f| %>
<%= f.label :name, "Name" %><br />
<%= f.text_field :name, placeholder: "Name" %><br />
<%= f.label :description, "Description" %><br />
<%= f.text_area :description, placeholder: "Description" %><br />
<%= f.label :with_codes, "Type" %><br />
<%= f.select :with_codes, [['Without Codes', false],['With Codes', true]], :selected => :with_codes %><br />
<div id="row_dim">
<%= f.submit "Manage Codes" %><br />
</div>
<script>
$(function() {
$('#row_dim').hide();
$('#with_codes').change(function(){
if($('#with_codes').val() == true) {
$('#row_dim').show();
} else {
$('#row_dim').hide();
}
});
});
</script>
<%= f.submit "Draft" %>
<%= f.submit "Save" %>
<% end %>
This script only hides my submit button, but I think there is a problem with recognizing selected value in form.
Upvotes: 0
Views: 235
Reputation: 2460
try this
<script>
function(){
$('#row_dim').hide();
$('#with_codes').change(function() {
if($('#with_codes').val() == true)
{
$('#row_dim').show();
}
else
{
$('#row_dim').hide();
}
});
}()
</script>
Upvotes: 0
Reputation: 163
Or maybe like this (more concise):
$(function() {
$("#row_dim").toggle($("#discount_with_codes").val() == 'true');
$("#discount_with_codes").change(function() {
$("#row_dim").toggle($(this).val() == 'true');
});
});
EDIT: Whoops, looks like you've already accepted the answer. But I'll leave mine here anyway.
Upvotes: 1
Reputation: 4888
First of all: are you sure that the select has id with_codes
and not discount_with_codes
?
Second thing, you should compare the value of the select as a string. Taking these two issues into account, the following code should work:
<script>
$(function() {
$('#row_dim').hide();
$('#discount_with_codes').change(function(){
if($('#discount_with_codes').val() == 'true') {
$('#row_dim').show();
} else {
$('#row_dim').hide();
}
});
});
</script>
Upvotes: 2