Entries Tagged as 'JavaScript'

Custom jQuery Validate Rule For Making Sure One Date is Later Than Another

JavaScript , jQuery 1 Comment »

In addition to providing a number of standard validation rules, the jQuery Validation plugin also allows you to create your own validation rules via the addMethod() function.ᅠ Today I had a situation where I had to use that function:ᅠ I had to create a rule to ensure that the end date of a date range determined by the user was later than the starting date.ᅠ I thought I'd share what I came up with.

The details of the situation:

  • The user set the starting date using two radio buttons and a text field bound to the jQuery UI Datepicker.ᅠ Selecting the first radio button meant that the start date (the "now" button) should be set to the current date, while selecting the second radio button (the "later" button) meant that the starting date would be determined by the value in the Datepicker field.
  • The user set the ending date using another Datepicker-bound text field.
  • The Datepicker plugin ensures that the date is always in the format "mm/dd/yyyy".

Here is the code:

jQuery.validator.addMethod("dateComparison",function(value,element) {
    var result= true;			
    if($("#startDateOptionLater:checked").length== 1) 
      {
        var dateArray= $("#startDate").val().split("/");
        var startDateObj= new Date(dateArray[2],(dateArray[0]-1),dateArray[1],0,0,0,0);
      } 
    else 
      {
        var exactDate= new Date();
        var year= exactDate.getFullYear();
        var month= exactDate.getMonth();
        var day= exactDate.getDate();
        var startDateObj= new Date(year,month,day,0,0,0,0);
      }
				
    var endDateArray= $("#endDate").val().split("/");
    var endDateObj= new Date(endDateArray[2],(endDateArray[0]-1),endDateArray[1],0,0,0,0);
    var startDateMilliseconds= startDateObj.getTime();
    var endDateMilliseconds= endDateObj.getTime();
				
    if (endDateMilliseconds <= startDateMilliseconds) 
      {
        result= false;
      }
     
    return result;

 },"The ending date must be a later date than the start date");

So if the user selected the second start date option and chose a date using the Datepicker widget, the code splits up the date string into an array and uses the individual month, day, and year values to create a Date object. If the user selects the option of making today the starting date, a new Date object is created (which by default has the value of the current date and time) and the code creates a new Date object with the same date but with the time-specific data stripped out (because the end date will not have a time value attached to it).

The Date object for the end date is created with the same technique used for the second start date option, and then the getTime() function is used on both the start and end Date objects to get the number of milliseconds between each date and January 1, 1970 (a starting point for date and time values used in both JavaScript and Java). Then it does the comparison between the two dates.

It's then a simple matter of applying this custom method somewhere within the normal jQuery Validation rules block:

...
rules: {
    endDate: {
      required: true,
      dateComparison: true
    }
...

Quick Tip: Use jQuery live() Function For Links in JavaScript-Powered Data Tables

JavaScript , jQuery No Comments »

NOT doing the tip that I'm about to share has bitten me twice now, so I'm putting this out there as a reminder to myself as well.

The jQuery live() function is an extremely useful function to have when you're adding or removing page elements that have jQuery event handlers assigned to them because using live() ensures that any new element that matches the live() selector gets that event handler automatically.

It's easy to remember to use live() when you're writing your own code that adds and removes DOM elements, but when you're using a plugin that does the adding and removing behind the scenes, you might not think about it.ᅠ In one of my applications, I apply the jQuery DataTables plugin to my HTML tables so that the users can sort and filter the data in the tables.ᅠ Included in each row are hyperlinks that trigger certain actions via JavaScript/jQuery.ᅠ

When I originally assigned the event handlers to these links, I simply used the "click" event handler on them.ᅠ The links worked perfectly if they were displayed as part of the initial page load, but any links belonging to rows that appeared later (as the result of a sort, filter, or pagination event in the plugin) did not work because the link elements were actually added by the plugin, and hence did not have the event handlers assigned to them.

In short, if you're using one of the many plugins to enhance HTML tables, and you have elements in each row that have jQuery events assigned to them, make sure you use the live() function to assign those event handlers.

jQuery UI 1.8: The Newly Arrived, and the Coming Soon

JavaScript , jQuery 3 Comments »

This past Wendsday, I attended the first jQuery UI meetup at the Microsoft office in downtown Washington D.C. The sole presenter for the meeting was Richard Worth, one of the members of the jQuery UI development team, who spoke to us about the new features in the latest release of jQuery UI, version 1.8...and mentioned a few things that were planned for the next release.

Read more...

HTML 5 Geolocation Functions and Mobile Web Browsers: Show the User Where They Are (Sort Of)

JavaScript , Miscellaneous , Web development , Android 7 Comments »

Every April, the University of Maryland holds a huge open-house event called Maryland Day that draws 60,000+ visitors to the campus to view exhibits highlighting the research conducted at the university and participate in various events and activities. All of the event details are entered into a ColdFusion application, and one of those details is the GPS coordinates (latitude and longitude) of where each event is taking place so visitors to the website can see where the events are located on Google Maps.

Now that smartphones are becoming more prevalent, I wanted to see if it was possible to build a web application that would show the user where they were currently located and then show them on a map how to get from their current location to a particular event.

So I did some research and learned that HTML 5 comes with a Geolocation API. This API allows you to execute Javascript functions within the navigator.geolocation object built into the browser that retrieve the supposed latitude and longitude coordinates of where the browser is located (and, if available, the altitude, heading, and speed at which the browser is moving).

Using the code examples I found on the Gelocation API page on the W3C website and on Oliver Wehren's geolocation demo page, I was able to create my own test page for determining my location and marking it on Google Maps. I then tried using the page with my Motorola Droid, my iPod Touch, and my manager's iPhone.

The default web browsers on all three devices implemented the Geolocation API (my preferred browser on my Droid, the Dolphin Browser, did not). Each of the browsers displayed a confirmation dialog asking for permission to share my location information with the web page (as mandated by the standard), and once I permitted the information to be used, my test page was able to place a marker denoting my location on the map.

However, the location wasn't as accurate as I had hoped. Although the API was coded to accept location data from the on-board GPS system in a mobile device, neither the iPhone nor the Droid seem to provide GPS data to the browser. If I was connected to the campus wireless network, my location was determined via the network topography, and it could be off by as much as 150 feet or so. The accuracy was even worse if I was relying solely on 3G: in that scenario, but the iPhone and the Droid had me located on the side of a state road on the outskirts of campus, a good twenty minute walk from where I actually was. I have no idea what caused both devices to pick that particular spot, as there certainly wasn't a cell tower anywhere near that location.

So I came to the conclusion that while the Geolocation API could be used to determine what town, city, or general area a user was currently in, it wasn't accurate enough (at least with these browsers in these devices) to provide walking or driving directions within a small area, especially given the fact that many of the users for the service I had in mind would only have access to the Internet via a 3G connection.

But if someone knows of a way of increasing the location accuracy of the Geolocation API, a way that doesn't require the end-user to modify their mobile browser in order to make it work, I'd love to hear about it.

Soft Deletes Verses Real Deletes When Doing CRUD Interactions

JavaScript , Web development , jQuery 5 Comments »

I happened to stumble across a blog post today by Phil Haack with the title "Death to confirmation dialogs with jquery.undoable." In it, Phil explained how he was inspired to write his plugin by seeing how his Netflix queue allowed him to "undo" the deletion of an item from the queue. As he said in his post:

"Notice that thereメs no confirmation dialog that Iメm most likely to ignore questioning my intent requiring me to take yet one more action to remove the movie. No, the movie is removed immediately from my queue just as I requested. I love it when software does what I tell it to do and doesnメt second guess me!"

His post got my attention because I'm currently in the middle of designing a scaffolding/code generation system, specifically to output pages for performing CRUD (Create, Read, Update, Delete) tasks, and it's currently designed so that when the user clicks on a "delete" link for a record (and Javascript is enabled), I make the user confirm their decision via a customizable dialog box (via the jqModal jQuery plugin) before proceeding with the deletion.

So I got to thinking about what would be involved in doing what he was suggesting: allowing the user to "delete" a record without confirmation as long as they had the option of undoing that action while still on the page.

I put "delete" in quotation marks because such a process would almost certainly involve making the delete a "soft" delete: marking/tagging the record as being deleted but not actually deleting the underlying database record. Undoing an actual deletion would be much harder, given that you would lose the unique record id in the deletion in addtion to the rest of the record data. I suppose you could potentially store the data from the record client-side (in the page) so the "undo" record could recreate the record from scratch, but that would be a pain and might not be feasible in every scenario. Undoing a soft delete/changing the delete flag in the record, on the other hand, would be pretty easy.

But if I went the soft delete routine, then the question would become: how do those records get deleted for real? I tend to design my web applications with a long term view, and I don't want the application database tables to fill up with deleted records over a number of years. My clients typically only have access to the database tables via the application itself, so leaving that up to them is not an option. So I would either have to given them another page/tool in the web application (perhaps a tool restricted to a tech-savvy few) to actually remove the deleted records, or perhaps run a scheduled task to remove those database records that have been marked for deletion for a year or more.

After some consideration, my current inclination is to stay with my current confirmation dialog/deletion routine. In most of my applications, the CRUD interactions are reserved for the administrative users of the application, who typically know when it's appropriate to delete a record. And the need to delete a record via the CRUD tools provided is usually rare, so having a confirmation dialog come up for each instance isn't too much of an annoyance.

But I'd be curious to hear other people's thoughts on this topic.