Matt Jones Matt Jones - 8 months ago 38
Ruby Question

Ruby on Rails - update fields based on f.select value

I have a dropdown box to chose the number of tickets that one wants to buy. I want to update the fields after it to reflect the value once it is clicked. Here is a snippet of my form currently:

<%= form_for :transaction, :url => new_transaction_path(:event_id => @event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select(:quantity, (1..20))%>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= @original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>


I want to replace (1) with the value from the f.select dropdown in the last table row to the value of guests that the user chooses.

EDIT WITH WORKING SOLUTION

<%= form_for :transaction, :url => new_transaction_path(:event_id => @event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select :quantity, (1..20), {}, { :onChange=>'mytest()', :id=>'quantitySelect' } %>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= @original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>


SCRIPT

<script type="text/javascript">
function mytest() {
var quantity = $('#quantitySelect').val();
$('#quantityRow').html("<h4><%= @original_event_price %> x (" + quantity + ") guest(s)");
}
</script>

Answer

You can do this with jQuery:

Let's add an id: "quantitySelect" on the quantity field Let's also add an id: "quantityRow" on the td field

$(function(){
  $('.quantitySelect').change(function(e){
    e.preventDefault();
    var quantity = $('.quantitySelect').val();
    $('.quantityRow').html("<h4><%= @original_event_price %> x (" + quantity + ") guest(s)");
  });
});

You can also add if checks to see if the quantity is > 1 and append the word guest to guests.