From 9dacfd1c7268c94c014173337ed51889cf25f43a Mon Sep 17 00:00:00 2001 From: Corey Frang Date: Wed, 27 Jul 2011 17:01:47 -0500 Subject: [PATCH] Mask: Initial draft of _caret, implementation borrowed from @digitalBush maskedInput plugin --- tests/unit/mask/mask.html | 2 +- tests/unit/mask/mask_core.js | 26 +++++++++++++++++++++++ ui/jquery.ui.mask.js | 41 ++++++++++++++++++++++++++++++++++-- 3 files changed, 66 insertions(+), 3 deletions(-) diff --git a/tests/unit/mask/mask.html b/tests/unit/mask/mask.html index 24cc12b6a67..f4c0d617249 100644 --- a/tests/unit/mask/mask.html +++ b/tests/unit/mask/mask.html @@ -32,7 +32,7 @@

    - +
    diff --git a/tests/unit/mask/mask_core.js b/tests/unit/mask/mask_core.js index ac0896c579e..c86e22eb3fe 100644 --- a/tests/unit/mask/mask_core.js +++ b/tests/unit/mask/mask_core.js @@ -2,4 +2,30 @@ module( "mask: core" ); +test( "_caret() can move and read the text cursor", function() { + expect( 3 ); + + var input = $( "#mask1" ).val("This string is 33 characters long").mask(), + instance = input.data( "mask" ); + input.focus(); + + instance._caret( 0 ); + deepEqual( instance._caret(), { + begin: 0, + end: 0 + }, "Caret position set to 0 results in 0, 0" ); + + instance._caret( 34 ); + deepEqual( instance._caret(), { + begin: 33, + end: 33 + }, "Caret position set beyond bounds (34) results in 33, 33" ); + + instance._caret( 0, 2 ); + deepEqual( instance._caret(), { + begin: 0, + end: 2 + }, "Caret position set to 0, 2 results in 0, 2" ); +}); + }( jQuery ) ); diff --git a/ui/jquery.ui.mask.js b/ui/jquery.ui.mask.js index a7ccbdf414e..6957ed23982 100644 --- a/ui/jquery.ui.mask.js +++ b/ui/jquery.ui.mask.js @@ -18,8 +18,45 @@ $.widget( "ui.mask", { }, _create: function() { + }, + + // helper function to get or set position of text cursor (caret) + _caret: function( begin, end ) { + var range, + elem = this.element, + dom = elem[0]; + + // if begin is defined, we are setting a range + if ( begin !== undefined ) { + end = ( end === undefined ) ? begin : end; + if ( dom.setSelectionRange ) { + dom.setSelectionRange( begin, end ); + } else if ( dom.createTextRange ) { + range = dom.createTextRange(); + range.collapse( true ); + range.moveEnd( "character", end ); + range.moveStart( "character", begin ); + range.select(); + } + } else { + + // begin is undefined, we are reading the range + if ( dom.setSelectionRange ) { + begin = dom.selectionStart; + end = dom.selectionEnd; + } else if ( document.selection && document.selection.createRange ) { + range = document.selection.createRange(); + + // the moveStart returns the number of characters it moved as a negative number + begin = 0 - range.duplicate().moveStart( "character", -100000 ); + end = begin + range.text.length; + } + return { + begin: begin, + end: end + }; + } } }); - -})( jQuery ); \ No newline at end of file +}( jQuery ) );