I have a Registration model and form which uses a datepicker. I want the user to be only able to select dates which correspond to events (another model).
My problem is I can’t find the right way to pass the event array to javascript.
this is in the controller:
@available_dates = Event.pluck(:start_time).as_json
this is in the view:
<script>
var availableDates = [<%= @available_dates.to_s.html_safe %>] ;
</script>
and this is the js:
function available(date) {
ymd = date.getFullYear() + "-" + ('0' + (date.getMonth()+1)).slice(-2) + "-" + ('0' + date.getDate()).slice(-2);
console.log(ymd+' : '+($.inArray(ymd, availableDates)));
if ($.inArray(ymd, availableDates) != -1) {
return [true, "","Available"];
} else {
return [false,"","unAvailable"];
}
}
$("#registration_date").datepicker({ beforeShowDay: available, dateFormat: "yy-mm-dd"});
I think I’m doing something wrong in the view since the js array seems to be empty looking at the console…
any help would be greatly appreciated
In the question comments you have mentioned
@available_dates.to_sreturns"[\"2013-01-05\", \"2013-02-02\", \"2013-03-02\"]". This itself will render the array on the page so no need to “box it up” again.Try changing the following line:
to this:
Hope it helps.
If it doesn’t you are either clearing the value of
@available_datessomewhere further in your code or@available_datesis not available in the context of your view. Have your tried stepping through the code usingdebugger;?