On focus, do customized focus on textarea
My Code:
$('#myTextArea').one('focus', function() {
$('#myTextArea')[0].selectionStart = 2;
$('#myTextArea')[0].selectionEnd = 6;
$('#myTextArea')[0].focus();
});
The code works fine, on focus (only once), it selects from index 2 to 6.
The problem: since this function is called on focus, it does the custom focus, but then it calls focus AGAIN and I lose focus of the selected text. Any po开发者_运维百科ssible solution?
I'm not exactly sure why this works but I think it might just do the trick:
$('#myTextArea').bind("focus mousedown", "click", function(event) {
event.preventDefault();
$(this).select();
this.selectionStart = 2;
this.selectionEnd = 6;
});
Try it here.
Since you're already binding to the focus
event and you aren't preventing the default behavior, you shouldn't need to fire .focus()
manually. Try this instead:
$('#myTextArea').one('focus', function(event) {
event.preventDefault();
this.selectionStart = 2;
this.selectionEnd = 6;
});
精彩评论