Formatting time for user input in ASP.Net MVC - 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.

Related

Angular Bootstrap UI Timepicker entering invalid time

I'm using Angular Bootstrap UI Timepicker and if I enter 50 in the hours field, it highlights the field red, but nevertheless I get a valid date out of it that looks just like that Tue Nov 15 2016 05:00:55 GMT+0100.
Any ideas what I can do? Thanks!
For that matter you could consider to limit the hour and minute input values, here is how to customize it for Timepicker
introduce a custom template and specify the min, max and validate-value attributes for hour and minute input elements, for example:
<input type="text" placeholder="HH" validate-value min="1" max="12" ng-model="hours" ng-change="updateHours()" class="form-control text-center" ng-readonly="::readonlyInput" maxlength="2" tabindex="{{::tabindex}}" ng-disabled="noIncrementHours()" ng-blur="blur()">
implement validate-value directive to limit the number values in input element:
.directive('validateValue', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.unshift(function(viewValue) {
var min = Number(eval(attrs.min));
var max = Number(eval(attrs.max));
var value = Number(viewValue);
var valid = (!isNaN(value) && value >= min && value <= max);
if (!valid) {
var currentValue = ngModelCtrl.$modelValue.toString();
ngModelCtrl.$setViewValue(currentValue);
ngModelCtrl.$render();
return currentValue;
}
else {
return viewValue;
}
});
}
};
})
Demo

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 make if loop in grails?

I'm beginner in Grails, please help. I have this in my gsp
<div class="right66">
<g:select class="time_pick" name="pick_day" placeholder="" from="${['Dani', 'Sati', 'Minute']}" valueMessagePrefix="book.category"/>
</div>
In translation: Dani = Days, Sati = Hours, Minute = Minutes. I need to save data in minutes but the user can choose if the input is in minutes, hours, or days. So I have to do if loop. I know how if loop works but I don't know how to write it in Grails. I was thinking something like this:
n=1
if(params.type=Dani){
n= 3600
}else if(params.type=Sati) {
n=60
}
def minute=params.minute*n
but how do I call that chosen input "Dani"? I can't write Params.type=Dani. Does if loop go in controller in my case?
If you need to convert your input to minutes, you should do that in your controller or a service. An if here is the same as in Java or Groovy. The inputs from your view will be in the params object in your controller with the same name as the input's id.
def minutes = params.input
if (params.pick_day in ['Sati', 'Dani']) {
minutes *= 60
if (params.pick_day == 'Dani') {
minutes *= 24
}
}
groovy solutions in your controller
you can use below for looping ,but when do you end the loop either you have to decremented or increment the value of n to an end value like say 1.upto(n) means 1...100 ,but every time iu change its value and ur infinite some where...
List types = []
types = params?.type
def minute = 0;
1.upto(n) {
if(types[i]=='Dani'){
n=3600
}
else if(types[i]=='Sati') {
n=60
}
minute = params?.minute*n
}

How do I call a JavaScript function from an html.erb

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()" %>

How to preselect an item using Javascript when the page renders

I have a drupal rendered webform that generates the following HTML for a SELECT list. The list is essentially for booking a table in a restaurant. My client wants me to preselect the meal based on the time of the day. So if its between midnight and 3:00 pm Lunch should be preselected automatically. After 3:00 pm till 10:30pm the form should display with dinner preselected.
<select class="form-select required" name="submitted[meal]" id="edit-submitted-meal">
<option selected="selected" value="1">Lunch</option>
<option value="2">Dinner</option>
<option value="3">Sunday Dining</option>
</select>
I created the following JS snippet hoping to achieve the objective but it doesn't seem to work on Page load
window.onload() {
var today = new Date("<?php echo date("Y-m-d H:i:s"); ?>");
var day = date.getDay();
var hour = date.getHours();
var meallist = document.getElementbyId("#edit-submitted-meal");
if (day == 0) {
meallist.options[3].selected==true;
}
else {
if (hour > 15 && hour < 22) {
meallist.options[2].selected==true;
}
else if (hour > 22 && hour < 24 {
meallist.options[1].selected==true;
}
else if (hour > 0 && hour < 15 {
meallist.options[1].selected==true;
}
}
}
Would appreciate any help. Thank you in advance.
PS : The PHP code injects the date into the javascript so when the page is rendered the line becomes var today = new Date("2013-01-15 15:49:45");
You have an error in your javascript syntax
window.onload(){
//your code here
}
should be
window.onload = (function(){
//your code here
});
Also when using document.getElementById you don't want to include the '#'
and for setting a variable as in
meallist.options[1].selected==true;
you only want to use a single =
meallist.options[1].selected=true;
Also bear in mind that the options array is 0 based. E.g options value=3 is actually
meallist.options[2] not [3]
A simplified version can be found here
http://jsfiddle.net/N7Yhr/
Do you have any other errors in your console window (firebug etc)?

Resources