How do you setup a select element to change the maximum value of a number field element on a change of value?
I want to change the max value of the passenger number field when the flight ID is changed.
This is my code so far. As you can see, I added the onchange at the end of the select layout.
<div class="field">
<%= form.label :flight_id %>
<%= form.select :flight_id, options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id), onchange: 'getMaxCapacity()' %>
</div>
<div class="field">
<% qty = @reservation.passengers %>
<%= form.label :passengers %>
<%= form.number_field :passengers, :id => 'passengers', min: 1, onchange: "calculateTotalPrice()", oninput: "calculateTotalPrice()" %>
</div>
My Javascript function getMaxCapacity() never gets entered. In the function I am setting the max value of the 'passengers' number field to the capacity variable.
<script type="text/javascript">
var capacity = {
<% Flight.all.each do |flight| %>
'<%= flight.id %>': <%= flight.capacity %>,
<% end %>
};
function getMaxCapacity() {
document.getElementById('passengers').max = capacity;
}
var costs = {
<% Flight.all.each do |flight| %>
'<%= flight.id %>': <%= flight.cost %>,
<% end %>
};
function calculateTotalPrice() {
var price = costs[document.getElementById('reservation_flight_id').value];
document.getElementById('cost').value = document.getElementById('passengers').value * price;
}
</script>
The signature of the FormBuilder#select
looks like this:
select(method, choices = nil, options = {}, html_options = {}, &block)
This means html_options
are the fourth parameter. Because you do not have any options
for the select
method you need to pass an empty hash as a third parameter.
<%= form.select(
:flight_id,
options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id),
{}, # empty options
onchange: 'getMaxCapacity()' %>. # here the HTML options
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.