How do I call a JavaScript function from an html.erb - ruby-on-rails

How do I call a JavaScript function from html.erb
in application.js
function displayClock() {
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var amOrPm = 'AM';
if (hours > 11) amOrPm = 'PM';
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
if (minutes <= 9) minutes = '0' + minutes;
if (seconds <= 9) seconds = '0' + seconds;
dispTime = '<b>'+hours + ':' + minutes + ':' + seconds + ' ' + amOrPm+'</b>';
document.getElementById('time').innerHTML = dispTime;
setTimeout('displayClock()', 1000);
}
and in home.html.erb
displayClock();
but it's not calling function!

You probably need to use proper tag to indicate that you're writing JS code:
<script type="text/javascript">
displayClock();
</script>
Plus, since you probably use jQuery (it's default in Rails), you may want to make sure the function is called after whole document is loaded:
<script type="text/javascript">
$(document).load(function(){
displayClock();
});
</script>
I'd also advice you not to write your JS in application.js and use this file only as a manifest file, which includes your other scripts through Rails asset pipeline.
Also you can take advantage of the javascript helper javascript_tag in your html.erb file
<%= javascript_tag "displayClock()" %>

Related

How to count time on rails

<h1>TIME: <%= Time.now.strftime("%H:%M:%S") %></h1>
In the template, my time is stopped. I want to animate it time like a digital watch.
The time is changed when I refresh a page.
For example, I'm going to index page and now the time shows: 12:30:50 (HH:MM:SS). I refresh again and the time shows: 12:31:10.
I want to show my seconds like this: 50 51 52 53 54.....
function displayTime() {
var timer=document.getElementById('timer');
var currentdate = new Date();
var hours = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
timer.innerHTML = hours + ':' + ("0" + minutes).slice(-2) + ':' + ("0" + seconds).slice(-2);
};
setInterval(displayTime, 1000);
<h1>Time :
<p id="timer">
<%= Time.now.strftime("%H:%M:%S") %>
</p>
</h1>
First, let's create a function that displays the current date. For this, we just have to find the p tag we are interested in (using getElementById), and put use innerHTML to write in it. That's the function displayTime.
Then, we want to run this function every second, so we use : setInterval.
Note I keep <%= Time.now.strftime("%H:%M:%S") %> so that if javascript is not enabled there is still a date. If that's not the intended behavior then you can replace it.

How to get current year with coffeescript

I am working with Angular/CoffeeScript/Rails and I am trying to place the copyright with the current year in the footer.
With JavaScript, I used to do something like this:
<script type="text/javascript">
<!--
var theDate = new Date();
$('.mDate').html('© ' + theDate.getFullYear());
-->
</script>
<span class="mDate"></span>
Here is what I have tried in CoffeeScript - within the mainController.coffee:
# mCopyRight
# ------------------------------------------------------------
$scope.mCopyRight = ->
$scope.theDate = new Date();
$scope.mFullYear = '© ' + theDate.getFullYear();
Within the application.html.erb
<span class="mDate">{{mFullYear}}</span>
But nothing is showing up.
It is like new Date is not working and/or .getFullYear(); either
The only thing that I can think of, would be to make a regular js file and require it in the application.js file:
//= require user-defined/mDate
With a file named mDate.js being in the vendor/assets/javascripts/user-defined/ directory.
Thanks in advance
You have assigned theDate to be a property of $scope. Either read it from there:
$scope.mCopyRight = ->
$scope.theDate = new Date
$scope.mFullYear = '© ' + $scope.theDate.getFullYear()
Or if that value is only needed by this function, don't use $scope:
$scope.mCopyRight = ->
theDate = new Date
$scope.mFullYear = '© ' + theDate.getFullYear()

jQuery UI Datepicker - Disable specific days selected from database not from arrays

Thanks in advance for your cooperation,
I'm using this JQUERY Date picker as shown in this image :
http://techblog.willshouse.com/wp-content/uploads/2009/06/datepicker.jpg
and for more information :
I have an ASP.net site retrieving data from SQL server 2008..
one of the admin functionalities is to change official holidays dates and save them in the DB in table Holidays
my question is:
how to disable these official holidays in the datepicker , so i prevent the user to select these specific days.
following this link:
jQuery UI Datepicker - Disable specific days
but I’m afraid I can’t use this solution manner , because the official holidays can’t be listed in an array since they are changed periodically many times by the admin of the site.
So, I don’t need to add them to the array list every time the admin change them.
I mean, is there any way to disable the selected dates from the table "Holidays" in the database?
Thanks in advance,
--- and also , i try to use this answer...
/* create an array of days which need to be disabled */
var disabledDays = ["2-21-2010","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"];
/* utility functions */
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1 || new Date() > date) {
//console.log('bad: ' + (m+1) + '-' + d + '-' + y + ' / ' + disabledDays[i]);
return [false];
}
}
//console.log('good: ' + (m+1) + '-' + d + '-' + y);
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
/* create datepicker */
jQuery(document).ready(function() {
jQuery('#date').datepicker({
minDate: new Date(2010, 0, 1),
maxDate: new Date(2010, 5, 31),
dateFormat: 'DD, MM, d, yy',
constrainInput: true,
beforeShowDay: noWeekendsOrHolidays
});
Here is a way to disable specific dates from being selected:
jQuery - Datepicker - Disable Specific Dates
Looking at the array in this link, instead of:
var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];
You would have something like:
<?php
$result = mysql_query("SELECT `date` FROM `Holidays`;")
foreach ($result as $holiday){
//may need to format $holiday here before using
$dates .= "'".$holiday."',";
}
//remove the last comma
$dates = substr($dates,0,-1);
?>
var unavailableDates = [<?php echo $dates; ?>];
Perhaps someone else can provide an ASP.NET solution?
For anyone's interest, here is how I did it with ColdFusion
<cfquery name="qHolidays" datasource="#ds#">
SELECT holiday_date
FROM public_hols
ORDER BY holiday_date
</cfquery>
<cfset disabledDays = '"1-1-2000"'>
<cfloop query="qHolidays">
<cfset disabledDays = disabledDays & ',"' & DateFormat(holiday_date,'d-m-yyyy') & '"'>
</cfloop>
<cfoutput>
<script type="text/javascript">
/* create an array of days which need to be disabled */
var unavailableDates = [#disabledDays#];
//var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
day = date.getDay();
if ( $.inArray(dmy, unavailableDates) < 0 && (day > 0) && (day < 7) ) {
return [true,"","Work Day"];
} else {
return [false,"","Public Holiday"];
}
}
/*
$('##iDate').datepicker({ beforeShowDay: unavailable });
*/
jQuery(document).ready(function() {
$(function() {
$('##dateentered').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
numberOfMonths: 3,
constrainInput: true,
beforeShowDay: unavailable
});
});
});
</script>
</cfoutput>

Formatting time for user input in ASP.Net MVC

I have a form that users are allowed to enter time values in (say, hours spent performing some task). A business requirement is that the time be entered in either hh:mm format, or decimal format. In either case, there could potentially be quite a bit of client side javascript for display "helping"--showing totals, validating against other input, etc.
So, for instance, one user might enter "8:30" for Eight Hours Thirty Minutes, while another might enter "8.5" to mean the same thing. I'm looking for something that would let me keep the form/validation duplication to a minimum.
What are the best ways to go about this with the model and the view?
The regular expression to allow both formats wouldn't be that complicated. I would perform that simple validation client-side via javascript. Beyond that, you may want to add some business validation (at the business object level) for this.
I used jQuery to create a slider that would change the time in the input box in the right format.
In my View File, Create.aspx, put the following jquery function somewhere in the beginning of the body.
<script>
$(function () {
$("#slider").slider({
value: 9,
min: 0,
max: 1440,
step: 15,
slide: function (event, ui) {
var hours = Math.floor(ui.value / 60);
var minutes = ui.value - (hours * 60);
var ampm = "AM";
if (hours == 12) { ampm = "PM"; }
else if (hours == 0) { hours = 12; ampm = "AM"; }
else if (hours > 12) { hours = hours - 12; ampm = "PM"; }
if (hours < 10) hours = '0' + hours;
if (minutes < 10) minutes = '0' + minutes;
$("#work_StartTime").val(hours + ':' + minutes + ' ' + ampm);
}
});
});
</script>
then down in the body of the same page put a div near the textbox for time input. A slider will show up at that div
<div class="editor-field">
<%: Html.EditorFor(model => model.work.StartTime)%>
<div id="slider"></div>
<%: Html.ValidationMessageFor(model => model.work.StartTime)%>
</div>
this will give you a slider. In the above javascript code change the step:15, makes increments to be 15 minutes.
This is obviously a client side validation. A server side validation should also be implemented of course.

jQuery UI - Datepicker - Hide year

I'm using jQuery UI 1.8 and I would like to hide the year from the user in both the popup and the textbox. Essentially instead of picking the day, month and year I want the user to just pick the day and month.
Hiding the year in the textbox is easy enough, the code shown below will do that. I'm stumped on how to hide the year from the popup - so it would say "April" instead of "April 2010".
$(function() {
$("#beginDateRange").datepicker({ dateFormat: 'mm/dd' });
});
<input type="text" name="beginDateRange" id="beginDateRange" />
Any help would be greatly appreciated.
I came across this thread in my search for a good way to do this, and here's what i came up with.
in my css i have a
.BirthdayDatePicker .ui-datepicker-year
{
display:none;
}
and this is how i set up my datepickers that i don't want to show the year on:
$('.DateTextBox.NoYear').datepicker({
beforeShow: function (input, inst) {
inst.dpDiv.addClass('BirthdayDatePicker');
},
onClose: function(dateText, inst){
inst.dpDiv.removeClass('BirthdayDatePicker');
}
});
basically i add the class just before it shows, and take it off when it hides it, so that other date pickers on the page arn't affected by it.
just incase anyone ever needs to hide the year only on specific pickers on a page and doesn't want to mess with the internals of jQuery.
I dont think this option is exposed va the api.
I belive that the easiest way is to change the stylesheet.
Change the ui-datepicker-year class to display: none
Another option would be to edit the source so it isnt rendered at all,
to do that you can remove this part of the code:
// year selection
if (secondary || !changeYear)
html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
else {
// determine range of years to display
var years = this._get(inst, 'yearRange').split(':');
var thisYear = new Date().getFullYear();
var determineYear = function(value) {
var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
var year = determineYear(years[0]);
var endYear = Math.max(year, determineYear(years[1] || ''));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
html += '<select class="ui-datepicker-year" ' +
'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
'>';
for (; year <= endYear; year++) {
html += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
html += '</select>';
}
I haven't tried removing the code but it should work.
I did try hiding it using css and that does work (in firefox anyway :) )
HTH
Very old question, but I just needed to do this myself and here's an alternate method that might be useful to somebody; a quick and dirty fix that will enable your other datepickers to continue working, provided you do NOT need the changeYear functionality is to set changeYear to true on the datepickers you DON'T want a year showing up, then add the CSS:
select.ui-datepicker-year { display:none }
VIKSME Hide year http://jsfiddle.net/tocv/e5cvA/
CSS
.ui-datepicker-year
{
display:none;
}
HTML
<div id="datepicker"></div>
</div>
JavaScript
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: false
});
});
The attribute
changeYear:false;
select.ui-datepicker-year { display:none }
sometimes change dropdown to span.<span></span>
So add this css code.
span.ui-datepicker-year { display:none }

Resources