31

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,684
  • 6
  • 27
  • 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

51

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,405
  • 10
  • 60
  • 80
Nicolas Modrzyk
  • 13,531
  • 2
  • 33
  • 39
  • I've updated the question, how would you add the trick to my current code, to replace the text? – skolind Oct 30 '11 at 09:30
  • 2
    This is the way to go! – klewis May 09 '14 at 19:42
  • Practically and with a new update from Jquery we should go like this ```$(document).on("click","#go_to_comments", function(e) { e.preventDefault(); $("#commentaire").focus() return false; })``` – John Max Feb 26 '18 at 21:09
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,684
  • 6
  • 27
  • 51
Ariel
  • 24,810
  • 5
  • 55
  • 69
0

You can use this :

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

Just use your input filed class name