开发者

jQuery: find which textbox has caret/is selected

开发者 https://www.devze.com 2023-01-29 20:10 出处:网络
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

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?


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())
});
0

精彩评论

暂无评论...
验证码 换一张
取 消