How to preselect an item using Javascript when the page renders - listbox

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)?

Related

Check what Date Format user uses

How can I check within my Rails app what datetime format the user currently uses as his default?
I have this method:
def local_date(date, am_pm = false)
unless am_pm
date&.localtime&.strftime('(%d.%m.%Y, %H:%M)')
else
date&.localtime&.strftime('(%d.%m.%Y, %I:%M %p)')
end
end
I need to set am_pm accordingly to users local machines datetime format WITHOUT relying on the :locale parameter as not everyone who speaks english uses am/pm
This is achievable in Rails only with the help of a bit of client side JavaScript code. The client side code would detect whether the user is using 24 hours time format or 12 hours time format, and then store that information of a cookie.
Your server side code should then read that information from the cookie and set your time format accordingly.
Add this to your app/assets/javascript/application.js file.
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
var dateString = date.toLocaleTimeString();
//apparently toLocaleTimeString() has a bug in Chrome. toString() however returns 12/24 hour formats. If one of two contains AM/PM execute 12 hour coding.
if (dateString.match(/am|pm/i) || date.toString().match(/am|pm/i) )
{
//12 hour clock
//check if we are already rendering in 12 hours format
if(getCookie("time_format") != "twelve")
{
document.cookie = "time_format=twelve";
/***
Now force the browser to reload current page from server.
Since we had set the the cookie, the server will now render
all pages in 12 hours format
****/
location.reload(true).
}
}
else
{
//24 hour clock
document.cookie = "time_format=twenty_four";
}
In your ApplicationController
class SomeController < ApplicationController
around_faction :set_time_format
def set_time_format
if cookie[:time_format]=="twelve"
#Set your desired time format string with 12 hour style
else
#default
#Set your desired time format string with 24 hour style
end
end
end

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 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
}

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