Appendix D. Creating decimal, currency, and time pickers with Globalize

In chapter 3 we discussed how to use the jQuery UI spinner widget to transform <input> elements into basic number pickers. Here, we’ll look at more complex usage scenarios of the spinner widget, including how to create decimal, currency, and time pickers.

To make this possible, the spinner widget uses another jQuery project known as Globalize. Globalize is a library that handles the formatting and parsing of various data types—strings, dates, numbers, and the like—in numerous cultures around the world. The spinner widget integrates with Globalize’s formatting and parsing to make these complex widgets possible. Let’s look at how, starting with decimal pickers.

D.1. Building decimal pickers

Keeping track of how various cultures handle something as simple as decimals is tricky because you have to know whether the culture use a period (1.23) or a comma (1,23) to delimit whole numbers from fractional numbers. Let’s assume you want to get a numeric value from a user that has two digits after the decimal mark. You could start with the following approach:

<input id="spinner">
<script>
    $( "#spinner" ).spinner({
        step: 0.01,
        page: 100
    });
</script>

This mostly works, but it has two problems. First, the spinner shortens trailing zeros. For instance, the whole number 1 displays as "1" rather than "1.00". Second, the spinner doesn’t use the correct delimiter based on the user’s culture. U.S. users expect to see a value of "0.25" to represent one quarter, but most European users expect to see "0,25".

The solutions to these problems lie in two of the spinner widget’s options—culture and numberFormat—which are used in tandem. The culture option accepts a Globalize culture. In general, culture codes are shorthand language codes—"en" = English, "es" = Spanish, "fr" = French, and "de" = German. The numberFormat option controls the format of the data that the spinner should use. The two most common formats are "n" for decimal numbers and "C" for currency values.

With this in mind, let’s see how you can alter your spinner to use these options. Before we look at the code, there’s one important thing to note: for space considerations, Globalize and its culture information aren’t stored on jQuery’s CDN. Therefore, you must download Globalize from https://github.com/jquery/globalize/releases (get version 0.1.1, as that’s the version this appendix uses), or from another CDN. Microsoft’s CDN has Globalize, and that’s what we use in the following listing.

Listing D.1. Creating spinners with decimal values

This example solves both of your previous issues. Because you set numberFormat to "n" , the spinner control knows you want to display a decimal value and always displays two decimal digits regardless of the number. You no longer see whole numbers such as "1". Second, because the culture is set to "de" (German) , the spinner uses a comma instead of a period to separate whole numbers from fractional numbers.

Note

Globalize has multiple number formats to handle values with different numbers of decimal digits. For example, n0, n1, n2, and n3 handle numbers with 0, 1, 2, and 3 decimal digits, respectively. For a full list of the formats Globalize can handle, refer to its documentation.

Tip

Don’t know the language the user speaks? You can grab that value from navigator.language and pass it to the culture option.

This updated spinner functionality is shown in figure D.1.

Figure D.1. Display of a decimal picker in the English and German cultures

The cool thing about using Globalize is that you don’t have to know which cultures use which conventions for handling decimal numbers—you just need to tell the widget which culture to use and let it handle the rest. The story is similar with another tricky data type: currency.

D.2. Building currency pickers

Currency has the same challenges decimal pickers have and more. In addition to knowing the period-versus-comma rules, you also need to know the appropriate currency symbol to use: the United States uses the dollar sign ($), much of Europe uses the Euro (€), Japan uses the Yen (¥), and so forth. In addition, some currencies have niche rules. For instance, the Yen can’t have fractional values. (There’s no such thing as half a Yen.)

To create a currency spinner, set the spinner’s culture option to the user’s culture and its numberFormat option to "C"—which stands for currency. The following listing shows a currency spinner that steps by a value of 25.

Note

You can play with this example live at http://jsfiddle.net/tj_vantoll/fC5j8/.

Listing D.2. A currency spinner
<script src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/
     globalize.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/cultures/
     globalize.cultures.js">
</script>

<input id="spinner" value="1025">
<script>
    $( "#spinner" ).spinner({
        step: 25,
        numberFormat: "C",
        culture: "de"
    });
</script>

Figure D.2 shows the display of the spinner in a variety of cultures.

Figure D.2. Display of currency spinners in German, English (U.S.), Japanese, and English (Great Britain)

That’s really all there is to it. Globalize ensured that the correct delimiters (decimal points vs. commas) were used, as well as the correct currency symbols. It even ensured that the Yen picker didn’t display fractional values automatically. If you want to get a consistent value, you call the spinner’s value() method. The following code returns 1025 for all the examples in figure D.2:

$( "#spinner" ).spinner( "value" );

Before leaving the topic of globalization, let’s look at another complex data type that Globalize can help with: times.

D.3. Building time pickers

Different cultures also have different ways of storing times. Unlike currencies, times are typically displayed in only two ways across cultures: with a 12-hour clock or a 24-hour clock. But even handling these two options can be tricky. The same time could display as 5:00 PM or 17:00 depending on where the user is located, and you don’t want to worry about which culture uses which format.

Unlike the earlier examples, the spinner widget doesn’t directly integrate time support. But you can add support to the widget with a little extra code. The following listing shows an approach that’s used on the jQuery UI demo site. (You can view the demo at http://jqueryui.com/spinner/#time.)

Listing D.3. A timespinner widget

This code creates a timespinner extension of the spinner widget . (You can read more about widget extensions in chapter 9.) To keep the timespinner’s value culture-independent, it’s stored as a millisecond value. You’ll see how to use the value momentarily, but knowing that the value is millisecond-based explains why you default the step and page options . You set step to 60000 because 60,000 milliseconds is 60 seconds, or one minute. You set page to 60 because there are 60 minutes (or steps) in an hour. This lets the user step the timespinner in one-minute increments (for example, 5:00 → 5:01 or 5:00 → 4:59) and one-hour increments (for example, 5:00 → 6:00 or 5:00 → 4:00).

The rest of the code converts between the millisecond value of the date and the formatted string that displays. The _format() method converts a millisecond value (passed in via the value argument) and converts it to a formatted string using Globalize’s format() method . The "t" argument you pass to format() tells Globalize to format the string as a time. The _parse() method does the opposite. It takes a formatted value (for example, "19:00" or "7:00 PM") and returns the millisecond value it represents . It calls Globalize’s parseDate() method to normalize the cultural difference.

With this in place, you can create a spinner using the following code:

<input id="spinner">
<script>
    Globalize.culture( "en" );
    $( "#spinner" ).timespinner();
</script>

Globalize.culture() sets the default culture so you don’t have to continuously tell Globalize which culture to use. By setting the culture to "en" (which defaults to U.S. English), you get a spinner that displays a 12-hour clock. Because the timespinner widget uses a millisecond representation under the hood, you can get the value to determine the user-selected time in a culture-agnostic way.

The following logs the spinner’s current hour:

var spinner = $( "#spinner" ),
date = new Date( spinner.timespinner( "value" ) );
console.log( date.getHours() );

This code logs 19, regardless of whether a spinner displays 7:00 PM (in the case of a culture with a 12-hour clock) or 19:00 (in the case of a culture with a 24-hour clock). The most common way of handling this situation is storing the timestamp in a server-side database. Figure D.3 shows the display of a few timespinner widgets. As you can see, the spinner can be initialized with a culture-specific string or a culture-agnostic timestamp.

Figure D.3. Display of four timespinner widgets. The top two use the U.S. English culture (which uses a 12-hour clock), and the bottom two use the German culture (which uses a 24-hour clock). The spinners can be initialized with a formatted string—7:00 PM or 19:00—or with a timestamp. In this example, the 1388566800000 timestamp represents a date with its hour set to 4 and its minutes set to 0.

Although we’ve focused on spinner integrations, these examples have showcased only some of what Globalize can do. Globalize handles number, decimal, percentage, currency, time, and date formatting in numerous cultures. And Globalize has no dependencies. You can use it with the jQuery UI widgets if you’d like, but you can use it to parse and format data in an application that doesn’t use jQuery at all. If your application is used by multiple cultures, it’s worth taking a look at Globalize’s documentation at https://github.com/jquery/globalize to see all you can do with it.

Why doesn’t datepicker use Globalize?

Unfortunately, datepicker and spinner use different globalization approaches; to use both, you have to import Globalize and its data, as well as datepicker’s locale scripts.

Datepicker is some of the oldest code in jQuery UI and therefore hasn’t been updated to modern conventions the library is using, such as Globalize. A rewrite of datepicker to use Globalize is in the works; you can monitor the progress at http://wiki.jqueryui.com/w/page/12137778/Datepicker.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.66.94