javascript - Rails pass generated js params from form to controller -
i have form_for 2 date fields , 1 integer.
:start, id: "start" :end, id: "end" :number_of_days, id: "number_of_days"my js:
$(document).ready(function(){ $("#start, #end").on('change', function () { var start = $('#start').datepicker('getdate'); var end = $('#end').datepicker('getdate'); var duration = (end.getdate() - start.getdate())/1000/60/60/24; $("#number_of_days").val(duration); }); });
the value of variable "duration" shows fine in :number_of_days field in form, how go on passing generated :number_of_days controller when submitting form?
thank you
edit: form_for:
<%= form_for(@vacation) |f| %> <div class="row"> <div class="large-2 columns"><%= f.label :start, "starts on" %></div> <div class="large-10 columns left"><%= f.text_field :start, data:{ type: 'date'}, id: 'start' %></div> </div> <div class="row"> <div class="large-2 columns"><%= f.label :end, "ends on" %></div> <div class="large-10 columns left"><%= f.text_field :end, id: 'end' %></div> </div> <div class="row"> <div class="large-2 columns"><%= f.label :number_of_days, "duration in days" %></div> <div class="large-10 columns left"><%= f.text_field :number_of_days, disabled: true, id: 'number_of_days' %></div> </div> <div class="row"> <div class="large-10 large-offset-2 columns"> <%= f.submit nil, class: 'button little radius success' %> </div> </div> <% end %>
controller action new , create:
def new @vacation = vacation.new end def create @vacation = vacation.new(vacation_params) @vacation.user = current_user @vacation.number_of_days = params[:number_of_days] respond_to |format| if @vacation.save format.html { redirect_to @vacation, notice: 'vacation created.' } else format.html { render action: 'new'} end end end
permit params in private:
def vacation_params params.require(:vacation).permit(:start, :number_of_days, :end) end
just looked @ form , noticed this:
<div class="large-10 columns left"><%= f.text_field :number_of_days, disabled: true, id: 'number_of_days' %></div>
you have disabled: true field when submit form value doesn't submitted. need update js file this:
$(document).ready(function(){ $("#start, #end").on('change', function () { var start = $('#start').datepicker('getdate'); var end = $('#end').datepicker('getdate'); var duration = (end.getdate() - start.getdate())/1000/60/60/24; $("#number_of_days").val(duration).attr("disable","false"); }); });
or
a improve solution create field readonly rather disabling it. by:
<div class="large-10 columns left"><%= f.text_field :number_of_days, readonly: true, id: 'number_of_days' %></div>
javascript jquery ruby-on-rails ruby ajax
No comments:
Post a Comment