Jquery Globalize format of number and Google Chrome - jquery-globalization

This fiddle return the correct value of "5,5" in both IE and FF but in Chrome it returns "5.5"
Fiddle: http://jsfiddle.net/4tvSH/
Globalize.culture("sv-SE");
alert(Globalize.format(5.5));
Is there a bug in the Globalize plugin?
edit:
This is strange, in Web.Config (MVC3) I have this
<globalization enableClientBasedCulture="true" />
Which means that the client sets the culture, both chrome and FF reports sv-SE, so the Globalize culture loaded is sv-SE like in the fiddle above.
But if i debug the code above on line 767 in Chrome
return culture.name.length ? value.toLocaleString() : value.toString();
value.toLocaleString() will return en-US format
This works, but its a hack..
//Fixes a bug in Globalize/Chrome where Globalize.format returns en-US format even with sv-SE
if($.browser.webkit == true) {
Globalize.orgFormat = Globalize.format;
Globalize.format = function(value, format) {
if(format == null) {
format = "N";
}
return this.orgFormat(value, format);
};
}

Chrome does indeed seem to handle value.toLocaleString() in a different way from firefox, however I believe this should be considered as a Globalize bug.
I have corrected this behaviour in my Globalize fork, which was as simple as removing that toLocaleString iirc.

Related

simpleWeather and moment.js - invalid date with js-geolocation in Germany

Hey ho =)
I wanted to create a Weather Plugin for my Website. So i choose the simpleWeather Plugin.
The simpleWeather Plugin used the moment.js lib to get the last updated time. But the Plugin itself not provide a language option.
My standard location is "Kiel, Germany".
But it's not working and says "Invalid Date".
I have no idea, why!
Can someone help me, please?
/* Does your browser support geolocation? */
if ("geolocation" in navigator) {
$('.js-geolocation').show();
} else {
$('.js-geolocation').hide();
}
/* Where in the world are you? */
$('.js-geolocation').on('click', function() {
navigator.geolocation.getCurrentPosition(function(position) {
getWeather(position.coords.latitude+','+position.coords.longitude); //load weather using your lat/lng coordinates
});
});
$(document).ready(function() {
getWeather('Kiel',''); //#params location, woeid //Get the initial weather.
});
function getWeather(location, woeid) {
$.simpleWeather({
//20065908 KIEL woeid
location: location,
woeid: woeid,
unit: 'c',
success: function(weather) {
html = '<ul>Today: <i class="icon-'+weather.code+'"></i><br />';
html += '<li>'+weather.temp+'°'+weather.units.temp+'</li>';
html += '<li>'+weather.city+', '+weather.region+'</li></ul>';
//Don't forget to include the moment.js plugin.
var timestamp = moment(weather.updated);
html += '<p>Weather updated '+moment(timestamp).fromNow()+'</p>';
html += '<p>Weather updated at '+moment(timestamp).format('MM/DD/YY h:mma')+'</p>';
for(var i=0;i<weather.forecast.length;i++) {
html += ''+weather.forecast[i].day+': <i class="icon-'+weather.forecast[i].code+ '"></i>';
}
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
}
codepen
I don't know how exactly the geolocation works... but I think that moment.js use the geolocation to set a language.
So I tried to set the moment.js locale globaly to 'en', but it's also not working how I expected.
The problem is that Yahoo Weather (simpleWeather's data source) does not follow its own standard for date formatting... The weather.updated date in the response looks like this: Tue, 20 Oct 2015 3:58 pm CEST. This is not a standard date format, thus Moment.js cannot parse is correctly (because there are some not unique time zone abbreviations, e.g. CST).
A quote from Yahoo Dev documentation:
pubDate: The date and time this forecast was posted, in the
date format defined by RFC822 Section 5, for example Mon, 25 Sep
17:25:18 -0700.
Clearly, this is not the case. Moment.js would happily parse RFC822 formatted date. Yahoo should fix this issue.
However if you really want to use this feature and you have a fixed location, there is a way to parse the local date from Yahoo by changing this line:
var timestamp = moment(weather.updated);
to this:
var timestamp = moment(weather.updated, "ddd, DD MMM YYYY HH:mm A");
And correct this date considering the visitor's time zone.

How to format date in a templatefield of a detailsview according to culture

I've been searching a lot on how to this
There is a lot of posts here and there on how to do it
However I cannot find a way to do what I want
I have this textbox in a TemplateField: (I cannot use a BoundField)
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("myDate", "{0:d/M/yyyy}") %>'>
That works good, but in my website i can change back and forth from english (us) to spanish (mx) so the date format is different and has to change as well.
en-US: M/d/yyyy es-MX: d/M/yyyy
how can i change that format in a postback?
I tried to have the TEXT intruction in a meta:ResourceKey but it displays '<%# Bind("myDate", "{0:d/M/yyyy}") %>' instead of the date
I also tried changing it from codebehind using: Text='<%# GetDate(Container.DataItem) %>'
public string GetDate(object dataItem)
{
DateTime dt;
DataRowView _row = (DataRowView)dataItem;
string fecha = _row["myDate"].ToString();
if (culture == "es-MX")
dt = DateTime.ParseExact(fecha, #"d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
else if(culture == "en-US")
dt = DateTime.ParseExact(fecha, #"M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);
return dt.ToShortDateString();
}
It does the trick but when I try to update or insert I get a null value error :/
Im using visual studio 2012 .net 4.5 and c#
Thanks for your help
rubenc
Well it turned out that this is a way of doing it
The null error was from another value :)
Thanks anyway

Set uiCulture automatically based on browser accept language

How I can set the culture of the ui automatically based on the users'browser?
All I found about this is Globalize.culture("pt-BR"); But it sets pt-BR as default and I dont want set this by default! I want only set this if the user is pt-BR!
How can I do this? And the validator methods, how can I set them for a specific culture?
In a ASP.NET MVC the web.config is the right place. There is a quick summary, the first snippet shows, how could be e.g. pt-BR culture forced
<globalization
enableClientBasedCulture="false"
uiCulture="pt-BR"
culture="pt-BR" />
If application is ready to accept the culture from the client (browser), settings should be
<globalization
enableClientBasedCulture="true"
uiCulture="auto"
culture="auto" />
The above setting will take a Language selected in client browser (e.g. cs-CZ in my case). If none is defined then system settings will be used.
Final snippet shows, how to allow client to set and send intended culture, but in case that no Language is pre-selected, override the system setting with some other default value pt-BR
<globalization
enableClientBasedCulture="true"
uiCulture="auto:pt-BR"
culture="auto:pt-BR" />
Extended: culture settings for jQuery validator and numeric input
Note: I am definitely not an expert in jQuery and globalization techniques. This is example how I do adjust validator to correctly process any numeric input
razor View part (X() is a shortcut for new HtmlString()):
var defaultThousandSeprator = "#X(culture.NumberFormat.NumberGroupSeparator)";
var defaultDecimalSeprator = "#X(culture.NumberFormat.NumberDecimalSeparator)";
jQuery part (custom methods for min and max)
$.validator.addMethod("min", function (value, element, param)
{
var num = value.replace(RegExp(" ", "g"), "") // remove spaces
.replace(RegExp('\\' + defaultThousandSeprator, "g"), "") // thousand separator
.replace(RegExp("\\" + defaultDecimalSeprator, "g"), "."); // fix decimals
return this.optional(element) || num >= param;
});
$.validator.addMethod("max", function (value, element, param)
{
var num = value.replace(RegExp(" ", "g"), "") // remove spaces
.replace(RegExp('\\' + defaultThousandSeprator, "g"), "") // thousands
.replace(RegExp("\\" + defaultDecimalSeprator, "g"), "."); // decimals
return this.optional(element) || num <= param;
});
And then jQuery.validator evaluates input values for cs-CZ: 10 000,00 correctly as well as en-US: 10,000.00.
You need to write out the script from the web page (or master page):
<script type="text/javascript">
Globalize.culture("<% = CultureInfo.CurrentCulture.ToString() %>");
</script>
That's it. Mind you, that I used CurrentCulture instead of CurrentUICulture, as this is what you should be using for formatting. If you need the translations (which I wouldn't do this way as it would hurt localizability), you'll need your original CurrentUICulture.

How to programatically set a date in jquery mobile Datebox plugin 1.1.0

I want to programmatically set date for the input with datebox control, For this i know i can use something like this
$(element).trigger('datebox', {'method':'set', 'value':'dateString'});
but this doesn't seem to update the control(i.e when i open the calendar, it is set to current date and not equal to the value in the input field)
EDIT:
based on JTsage's pointers i overwrote the default dateformat to mm/dd/yyyy, using sth like this.
jQuery.extend(jQuery.mobile.datebox.prototype.options.lang, {
'en': {
dateFormat: '%m/%d/%Y'
}
});
jQuery.extend(jQuery.mobile.datebox.prototype.options, {
useLang: 'en'
});
Then i tried setting the date using sth like this
$(element).trigger('datebox', {'method':'set', value:'07/02/2012'});
but this date is not appearing when i navigate to the page..Interestingly when i tried updating the date from firebug console(being on that page) it updated the field as well as datebox control.
I have no idea why this is happening..Need help, please respond JT
So finally i fixed the issue, by doing this
jQuery.extend(jQuery.mobile.datebox.prototype.options, {
'overrideDateFormat': '%m-%d-%Y',
'overrideHeaderFormat': '%m-%d-%Y'
});
setting the value of the input field explicitly
$(element).val('06-21-2012');
and then refreshing the datebox
$(element).trigger('datebox', {'method':'set', 'value':'06-21-2012'});
I found th solution, try this
$(element).trigger('datebox', { 'method': 'doset' });

jquerymobile form not working as expected on mobile browsers, but works on desktop browsers?

I am having a problem with my jqm form not working properly in mobile browsers (iPad 1 Safari, Android Dolphin) but working as expected in desktop browsers (Chrome, Firefox, Safari & IE9 on Win7).
The form starts by asking the user how they would like to be contacted (email, sms, and/or post), then updates fields to be required based on this selection (validation is via the validationEngine.js plugin).
An example of the form can be seen here.
The logic of the script is that it checks to see if the checkbox is selected (or de-selected), then adds (or removes) a class to make it required as shown below.
$('body').delegate('#byEmail_label', 'click tap', (function(event) {
if (!$("#byEmail").is(":checked"))
{
$('#req_email').addClass('reqField');
$('#email').addClass("validate[required,custom[email]]");
}
else
{
$('#req_email').removeClass('reqField');
$('#email').removeClass("validate[required,custom[email]]").validationEngine('hide');
}
})
);
I had this working 100% without the .delegate(), but then I could not have the form load via ajax - after adding .delegate it all works well, except in mobile browsers.
Has anyone experienced something similar, or have any idea how I can get this working?
Thanks
Finally fixed my own problem by moving all my jquery outside the
$(document).ready(function () {...
and into
$('*').delegate('body','pagecreate', function(){...
ie:
$('*').delegate('body','pagecreate', function(){
$('#byEmail_label').tap(function(event) {
if ($("#byEmail").is(":checked"))
{
$('#req_email').addClass('reqField');
$('#email').addClass("validate[required,custom[email]]");
}
else
{
$('#req_email').removeClass('reqField');
$('#email').removeClass("validate[required,custom[email]]").validationEngine('hide');
}
});
});
Now my head feels better... no more banging it on the desk...
I also had troubles with checkboxes and radios, this is what I used. Might help to check for the value instead of if it's checked.
alert($('input[name=byEmail]:checked').val());
or
var cb_val = $('input[name=byEmail]:checked').val() == true;
or
var cb_val = ($('input[name=byEmail]:checked').val() == 'blah') ? true:false;
Maybe something like this
var addValidation = ($('input[name=byEmail]:checked').val() != '') ? true:false;
if(addValidation) {
$('#req_email').addClass('reqField');
$('#email').addClass("validate[required,custom[email]]");
} else {
$('#req_email').removeClass('reqField');
$('#email').removeClass("validate[required,custom[email]]").validationEngine('hide');
}

Resources