33

I would like to place the cursor in an input field after a specific link is clicked. I'm using this for a small search engine.

Imagine an input field: []. Then some links which is adding a string like: Denmark, England etc. to the input field.

Now I need the cursor to be placed like this: "Denmark, [here]".

Is this possible?

* UPDATE *

I'm using this code right now to replace the text, how would you add the "position cursor"-trick with this?

$('#denmark').click(function(){     
   $('#searchBoxBig').val('Denmark, ');
});
skolind
  • 1,724
  • 6
  • 28
  • 51
  • 1
    Do you want multiple clicks to append or replace the text? – a'r Oct 30 '11 at 09:21
  • Replace the text.. I've updated the question with the text I use right now – skolind Oct 30 '11 at 09:28
  • If you also want to move the caret at the visible part of the browser, have a look at this answer: http://stackoverflow.com/questions/7892902/possible-to-scroll-caret-into-view-inside-a-single-html-text-field-with-javascri/7893633#7893633 – Rob W Oct 30 '11 at 09:42
  • Looks like it's already doing that? – skolind Oct 30 '11 at 09:46
  • 5
    @Al-Mothafar Take it easy dude.. Seriously :-D – skolind Nov 01 '11 at 09:07

4 Answers4

52

yes, catch the click event on the anchor prevent the default action and focus on the field.

the function context contains the element that has been clicked so u can compute which field to apply the focus call on.

$(anchorSelector).live("click", function(e) {
   e.preventDefault(); 

   $(fieldSelector).focus();

   return false;
});
472084
  • 17,666
  • 10
  • 63
  • 81
Nicolas Modrzyk
  • 13,961
  • 2
  • 36
  • 40
30

You can set where the cursor is in an input box with the selectionStart and selectionEnd properties. If you don't want any text to be selected, just make them equal to each other.

Here's how you might do it:

var input = $("input");
input[0].selectionStart = input[0].selectionEnd = input.val().length;
7
$(":input[name=xxxx]").focus();

Ah, you need the cursor to be after all the text? Take a look here: jQuery Set Cursor Position in Text Area it works the same for an input instead of a textarea.

This also works if you use other selectors.

skolind
  • 1,724
  • 6
  • 28
  • 51
Ariel
  • 25,995
  • 5
  • 59
  • 69
0

You can use this :

jQuery('.className').focus();

Just use your input filed class name