pejmanjohn
pejmanjohn

Reputation: 1057

Passing javascript date to rails form

At the top of a page I have a javascript datepicker. The selected date is stored in the variable newDate

Lower I have a form in rails like so:

<%= form_for(@checkin) do |f| %>
  ...
<% end %>

I want the date selected above to get passed as a parameter upon form submission. I want to do something like this:

<%= f.hidden_field :checkedin_at, :value => newDate %>

But I'm pretty sure I can't mix client-side and server-side code like this. Is there another way to pull this off?

Upvotes: 0

Views: 371

Answers (2)

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31477

You can create a hidden field like you did, and from javascript you can set the value of that hidden field to the actual value.

Erb part:

<%= f.hidden_field :checkedin_at, :value => '', :id => 'date' %>

Javascript part:

document.getElementById('date').setAttribute('value', newDate);

You can do javascript set part when you got the new date value or on submit it's your decision.

Modifying

If you want to modify an already saved checkedin_at variable later, then you need to read it before. So you may need to set the actual value in Erb from the model, and read with:

newDate = document.getElementById('date').getAttribute('value');

Sidenote

It's a good idea to do it in an unobtrusive way with javascript. To Be prepared for browsers without javascript support on people with disabilities who cannot use normal browsers.

So a simple HTML solution is a nice to have with visible date field with parsable (not a timestamp) date field.

Upvotes: 1

Prasad Surase
Prasad Surase

Reputation: 6574

on submit, u will have to copy the data field data to the hidden field and then submit the form. but if u want to submit the selected date when the form is submitted, its better to have the date as a visible and selectable field of the form.

Upvotes: 0

Related Questions