1

I have a page with several text inputs and several buttons. When I click a button I want the value of that button to be inserted at the caret, whichever field the caret is in. Here's my function call so far:

$('li input[type="button"]').click(function(){$('#aTextInput').insertAtCaret($(this).val())});

I want to replace $('#aTextInput') with the input that actually has the caret in it. Any ideas?

(Here's the insertAtCaret function, before anyone asks. You probably don't need to look at it unless you're curious.)

Edit:

So I tried this:

jQuery.extend(jQuery.expr[':'], {
    focus: "a == document.activeElement"
});

$('li input[type="button"]').click(function(){$('input:focus').insertAtCaret($(this).val())});

But when I click a button, nothing happens at all. Am I implementing this solution wrong?

Community
  • 1
  • 1
user460847
  • 1,578
  • 6
  • 25
  • 43
  • http://stackoverflow.com/questions/2683742/is-there-a-has-focus-in-javascript-or-jquery/2683838#2683838 – charliegriefer Dec 11 '10 at 08:28
  • I'd already seen that, but I can't get it to work. I'll edit my question to show how I tried to implement it--maybe I'm just doing it wrong. – user460847 Dec 11 '10 at 08:35

1 Answers1

3

If you have several textareas, you'd probably want to do something like this.

// any time a textarea gets focus, set the ID
$('textarea').focus(function(){
   focusID = $(this).attr('id');
});

// when the button is clicked
$('input[type="button"]').click(function(){    
    // insert the value into the textarea
    insertAtCaret(focusID,$(this).val())
});

Check out my example on jsFiddle here

The problem I had was, when the button is clicked the textarea loses focus, so it was hard to find the textarea that had focus at the moment the button was clicked.

EDIT

I just realized you were trying to do this with inputs, new jsFiddle here: http://jsfiddle.net/tVNDL/1/

// any time a input gets focus, set the ID
$('input').focus(function(){
   focusID = $(this).attr('id');
});

// when the button is clicked
$('input[type="button"]').click(function(){    
    // insert the value into the textarea
    insertAtCaret(focusID,$(this).val())
});
jyoseph
  • 5,435
  • 9
  • 45
  • 64