1

Following js look for the textfield q in queryform and focus it:

js:

if($("#queryform").length){ document.queryform.q.focus(); }

html:

<form id="queryform" name="queryform" action="" method="post"><input type="text" name="q" /></form>

current function

In chrome: textfield is found and focused and text is highlighted

In FF and IE: textfield is focused and marker is placed at the back

wanted function

Same in all browsers: textfield is focused, text not highlighted, marked at the end of the text

jquery

I already use jquery on the site so a neat jquery solution is preferable

Joseph
  • 1,734
  • 6
  • 29
  • 51

1 Answers1

2

See this soloution:

Use JavaScript to place cursor at end of text in text input element

The first soloution didnt work, but his script did, see http://jsfiddle.net/WcGLP/

(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange)
        {
        // ... then use it
        // (Doesn't work in IE)

        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);
Community
  • 1
  • 1
Marco Johannesen
  • 13,084
  • 6
  • 31
  • 36