Posts Tagged ‘jQuery’

Toggle non-consecutive checkboxes with jQuery UI

Posted on:Tuesday, December 27th, 2011 by Ashish Datta

You’re all probably familiar with the UI convention of allowing users to select ALL or NONE for a list of checkboxes (like in Gmail). Recently I was working on a project that had a large table full of checkboxes (imagine a 10×10 grid) where the user would need to toggle some but not all of the checkboxes in a given row. And to make matters more complex, they would need to toggle groups of non-consecutive checkboxes (say 15, skip 10, 5, etc.). I threw on the thinking cap but couldn’t think of any similar interactions I’d seen and couldn’t think of a particularly good way to achieve this.

Enter jQuery UI. I happened to stumble across the jQuery UI Selectable documentation and realized it would provide a good UI experience to toggle some but not all of the checkboxes. The code to implement this is surprisingly simple:

Note: You don’t actually need the div container – that was just for JSFiddle.

<div id="checkboxes">

<table id="checkboxTable">
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
</table>
</div>

And then the Javascript (jQuery + jQuery UI):

$("#checkboxes").selectable( {filter: "input:checkbox",
            stop: function(event, ui) {

                $(".ui-selected").each( function(){

                    $(this).each( function(){
                        var val = $(this).attr("checked") ? null : "checked";
                        $(this).attr("checked", val);
                    });

                });
}});

You can check out a live demo at http://jsfiddle.net/whMyQ/3/

As always, questions and comments are welcome!

jQuery UI confirm

Posted on:Monday, March 21st, 2011 by Ashish Datta

I was looking around earlier for a jQuery plugin to allow me to use jQuery UI’s dialog() widget to popup a confirm dialog. Didn’t have any luck finding one so I whipped something up. It’s not pretty but it works. You could even go as far as to overload window.confirm() but thats probably a bad idea.

jQuery.confirm = function(options){

	var opts = jQuery.extend( { message: "", ok: function(){}, cancel: function(){ } }, options );

	jQuery("
" + opts.message + "" + "
").dialog({ autoOpen: true, modal: true, autoOpen: false, resizable: false, draggable: false, title: "", width: "400px", buttons: { "Cancel": function(){ opts.cancel.call( this ); }, "Ok": function(){ opts.ok.call( this ); } } }).dialog("open"); }; // use it jQuery.confirm( { "message": "Are you sure?", "ok": function( ){ $(this).find(".loader:first").show(); // do stuff $(this).dialog("close"); }, "cancel": function( ){ $(this).dialog("close"); } });

iPhone style checkboxes for Symfony

Posted on:Wednesday, October 13th, 2010 by Ashish Datta

No one worry, I did in fact survive my birthday and subsequent party!

Anyway, I was poking around for some cool UI elements for checkboxes and stumbled across this neat jQuery plugin – http://github.com/tdreyno/iphone-style-checkboxes Basically, what it does is converts checkboxes into iPhone style toggles.

Check out a demo at http://tdreyno.github.com/iphone-style-checkboxes/

This is for a symfony project (shocker!), so I figured I’d roll it into a widget and share.

You’ll need to download and include the JS+CSS+images for the plugin yourself and then copy the following code into your project:


class sfWidgetFormInputiPhoneCheckbox extends sfWidgetFormInputCheckbox {

	public function __construct($options = array(), $attributes = array())
	{

		$this->addOption('checked_label');
        $this->addOption('un_checked_label');

		parent::__construct($options, $attributes);
	}

	public function render($name, $value = null, $attributes = array(), $errors = array())
	{
		$str = parent::render( $name, $value, $attributes, $errors );

		$checkedLabel = $this->getOption("checked_label");
        $uncheckedLabel = $this->getOption("un_checked_label");
        $id = $this->generateId($name);

		$str .= <<

		  $(document).ready( function(){

                $('#$id').iphoneStyle({
                    checkedLabel: '$checkedLabel',
                    uncheckedLabel: '$uncheckedLabel'
                });

		  });
		
EOF;

		return $str;
	}

}

Using it is straightforward:

    $this->setWidgets(array(
      'show-upcoming-events-nav' => new sfWidgetFormInputiPhoneCheckbox( array("checked_label" => "on", "un_checked_label" => "off") ),
    ));

Streaming Foursquare checkins with Google Maps

Posted on:Monday, September 13th, 2010 by Ashish Datta

This Saturday was the second annual Redline Challenge which is a bar crawl from Downtown Crossing to Davis Square that loosely tracks the MBTA Redline.

This year, we decided to use Foursquare to allow the website to track the position of several of the participants on the challenge. Foursquare natively allows you to track your checkin history with private URLs. Currently, they support a handful of formats with KML being the most interesting for our purposes. You can find your private URLs by navigating to http://foursquare.com/feeds/

We used the Google Maps API along with the KML stream from Foursquare to dynamically place markers on the map as different users checked in to different venues.

Here is the PHP we used to pull back the KML feed, transform it to JSON, and spit it back to our jQuery on the client side:

$xml = simplexml_load_file( "http://feeds.foursquare.com/history/myurl.kml" );
$arr["a"] = $xml->Folder;
$xml = simplexml_load_file( "http://feeds.foursquare.com/history/ackleysurl.kml" );
$arr["m"] = $xml->Folder;

echo json_encode( $arr );

Pretty straight forward. Here is the jQuery code on the client side to add markers to the map:

       $.getJSON( "location.php", {}, function(data){

    	   data.a.Placemark = data.a.Placemark.reverse();

         var hasStarted = false;
         var barIndex = 1;

         $.each( data.a.Placemark, function(i, val){

               if( val.published.indexOf("Sat, 11") == -1 ){
                    return true;
               }

               if( !hasStarted && val.name == "Setfive Consulting" ){
                  hasStarted = true;
               }else if( !hasStarted ){
                  return true;
               }

               var latLng = val.Point["coordinates"].split(",");

               var point = new GLatLng( latLng[1], latLng[0] );

               var marker = new GMarker(point);

               marker.bindInfoWindowHtml( "
" + barIndex + ". " + val.name + "
" ); map.addOverlay(marker); latLngList.push( point ); if( i == data.a.Placemark.length-1 ){ map.setCenter(point, 14); $(marker).click(); marker.openInfoWindowHtml( "
We are at " + barIndex + ". " + val.name + "
" ); } barIndex++; }); var polyline = new GPolyline( latLngList, "#ff0000", 5 ); map.addOverlay(polyline); latLngList = []; data.m.Placemark = data.m.Placemark.reverse(); var blueIcon = new GIcon(G_DEFAULT_ICON); blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; markerOptions = { icon:blueIcon }; barIndex = 1; $.each( data.m.Placemark, function(i, val){ if( val.published.indexOf("Sat, 11") == -1 ){ return true; } var latLng = val.Point["coordinates"].split(","); var point = new GLatLng( latLng[1], latLng[0] ); var marker = new GMarker(point, markerOptions); marker.bindInfoWindowHtml( "
" + barIndex + ". " + val.name + "
" ); map.addOverlay(marker); barIndex++; latLngList.push( point ); }); var polyline = new GPolyline( latLngList, "#001299", 5 ); map.addOverlay(polyline); })

That’s about it.

UPDATED: New Facebook Phonebook Script

Posted on:Monday, July 19th, 2010 by Ashish Datta

I realized this morning that Anonymous Coward’s Facebook Phonebook Greasemonkey script broke awhile back so I decided to rewrite it from scratch.

The original instructions for how to install the script are available here.

I updated the original Userscripts page with the new script so you can download it here.

Once again, this probably breaks your Facebook TOS so I can’t vouch for the safety of your account if you do decide to do this.

QR Bookmarklet

Posted on:Sunday, June 13th, 2010 by Ashish Datta

I got tired of having to find the same website (mostly recipes) on my phone after looking at them on my workstation or laptop so I decided to whip together a bookmarklet to throw a Google powered QR code on any page.

The bookmarklet will just slap a QR code image with the current page’s URL (window.location) so that you can open the page on your phone. ps. Barcode Scanner for Android will automatically open the URL in a browser.

Without further ado, QR Code Bookmarklet

jQuery.trigger weirdness

Posted on:Thursday, June 10th, 2010 by Ashish Datta

Earlier today, I was trying to use jQuery to trigger the submission of a form after a radio button was clicked. The form tag looked something like:

...form..

So for a regular submit button:


Everything works fine, you’ll see the alert() and the form won’t submit because of the return false.

I ran into issues when I tried to trigger() the submit event with jQuery. I was trying to trigger the submit() event on the form via jQuery. The problem I ran into, was that the saysomething() function was getting called, but the “return false” seemed to have no effect.

The final form looked something like:

For some reason, if you submit the form via a jQuery trigger the form submits even though saysomething() gets called. I’m not sure if this is the expected behavior but it was certainly something of a shock. Anyway, a live version of the form is running here.

Run jQuery each() serially

Posted on:Tuesday, May 18th, 2010 by Ashish Datta

jQuery.each() is pretty sweet but earlier today I wanted to run some animations across a set of three elements and since the animate() calls are non-blocking everything was happening at the same time. What I wanted to do was have the functions execute in a serial fashion (1 after the other).

I poked around and it doesn’t look like there’s a native way to do this. After a bit I decided to just whip something up and see how it works. Here’s what I had originally:

$("#splashStream .snippetbox").each( function(index){
	$(this).animate( {opacity: 0}, 1000, function(){
		$(this).html( $("#hiddenSplashDiv .snippetbox:eq(" + index + ")").html() );
		$(this).animate( {opacity: 1}, 2000 );
	});
});

That ran fine but everything happened at the same time. The modified serial code looks like:


                  var hasCallbackCompleted = [ true ];
                  $("#splashStream .snippetbox").each( function(index){

                      var f = arguments.callee;
                      var args = arguments;
                      var t = this;

                      if( !hasCallbackCompleted[ index ] ){
                        window.setTimeout( function(){ f.apply(t, args); }, 5 );
                        return true;
                      }

                      hasCallbackCompleted[ index + 1 ] = false;
                      $(this).animate( {opacity: 0}, 1000, function(){
                          $(this).html( $("#hiddenSplashDiv .snippetbox:eq(" + index + ")").html() );
                          $(this).animate( {opacity: 1}, 2000, function(){
                            hasCallbackCompleted[ index + 1 ] = true;
                          });
                      });

                  });

Basically, what it does is after the first element, the code will delay execution of the each() function until the hasCallbackCompleted flag is set for the correct element.

jQuery blank() modified for password fields

Posted on:Wednesday, April 28th, 2010 by Ashish Datta

We’ve been using Jeff Hui’s very awesome jquery.blank plugin for sometime over at Setfive HQ. What blank() is allow you to basically move the labels for text inputs into the input themselves (to save space). We use this technique frequently for login boxes in headers since it’s easier not to have to stick in labels next to text boxes.

The problem is, you can’t use blank() on a password field since a password field won’t display clear text (obviously). To get around this, I’ve always manually stuck in a “shadow” text box next to the password field and toggled the text box or password box in order to make blank() work correctly.

Anyway, I finally got tired of doing this so I decided to patch the plugin to do this automatically. Jeff incorporated the code back into blank() and it’s available on GitHub here.

Happy coding.

javascript – $(document).ready getting called twice? Here’s why.

Posted on:Monday, February 22nd, 2010 by Matt Daum

Recently we found ourselves having a really weird problem on a project: Every time a page was loaded it seemed a bunch of different Javascript functions were being called multiple times and making many widgets on the page break and we couldn’t figure it out. Some of the functions were our own code, some part of the package we were using. After a while we narrowed it down to that all the functions in the

$(document).ready(...);

we’re being called twice. We had never seen this. After about an hour of removing javascript files and just headbanging, and many thanks to Ashish, we found the root cause. We had written in a quick hack for a late proof of concept to string replace on the entire HTML of a page a specific string. We did it this way:

$('body').html($('body').html().replace(/{REPLACETEXT}/i, "More important text"));

Basically we used a regex to parse the entire HTML tree and then replace it with the updated text. Unknowingly this caused the document ready event to be triggered again(though now it makes sense), causing many widgets to get extra HTML.

Let this save you some headbanging.