1

Given the following:

   $("#dataField").focus().autocomplete({
        minLength:5,
        cache:false,
        source:"${request.contextPath}/ajaxActions/getdata",
        select:function (event, ui) {
            populateForm(ui);
        }
    });

How could I change the focus function such that it would place the cursor at the end of the input's current value?

barrymac
  • 2,750
  • 1
  • 20
  • 32

2 Answers2

1

I haven't actually tested this, but it should more or less do what you need.

(function( )
{
    var oldFocus = $.fn.focus;
    $.fn.focus = function( arg1, arg2 )
    {
        // ======== Call Old Function
        var result = oldFocus.apply( this, arguments );

        // ======== Additional Functionality
        // Logic here to move your cursor

        return result; // -- this preserves ability to chain
    }
})( );

For actually moving the cursor, see this SO question: move cursor to the beginning of the input field?

Community
  • 1
  • 1
KOGI
  • 3,959
  • 2
  • 24
  • 36
  • Great information thank you very much! When I test though it didn't focus the field, but soon as I get it working I'll edit and we can tick it then – barrymac Jan 10 '12 at 17:16
  • You may have copied the code here before I made an edit. Particularly the line where the oldFocus function is called. I am now using .apply( ) instead of jQuery's .proxy( ) -- should work now :) – KOGI Jan 10 '12 at 17:19
1

 

$("#dataField").focus(function() {
      $(this).val($(this.val());
 }).focus();

This approach is the jQuery way of doing the stuff in this link and thus should do what you require.

Community
  • 1
  • 1
Sunjay Varma
  • 5,007
  • 6
  • 34
  • 51
  • This is a great approach, but is not technically what was asked for. This solution creates an event handler so that if focus is ever granted to the element (by the user, or programmatically), then the cursor is moved (after the fact). The OP requested a way to actually modify the focus() method itself. – KOGI Jan 10 '12 at 17:16
  • Also, the method of moving the cursor used here (setting the value of the element) may or may not work from browser to browser due to variability of browser behavior. – KOGI Jan 10 '12 at 17:17
  • Thanks for the contribution, but I had to give the answer to Kogi for maintaining the chaining ability – barrymac Jan 10 '12 at 17:25