Allow user to select inside a textarea after it's been created by js
I have a div named "What". If the user clicks on it, it changes from text into a textarea input.
$('.What').click(function() {
$(this).empty().html('<textarea name="X">' + $(this).text() + '</textarea>');
$(this).find('textarea').select();
});
You can see that I also select the newly开发者_如何学Go created textarea.
If the user clicks into the textarea, nothing happens.Q: How can I allow the user to click into the newly created textarea field to position the cursor where they want to? I suspect it has something to do with using a live event to prevent bubbling.
The problem is, that your click handler does not disappear after you replace the content of your div with a textarea. So every click on the textarea bubbles up the the "What"-div and triggers your event handler again, which re-apppends the textarea.
You have to make sure that clicks on the textarea do not trigger your handler. An easy way to do this is jquery's one
-function, which unbinds your event handler after it has been called once.
Another issue with you fetch the content of your div after you empty it, so the default value of your textarea will always be an empty string. This can be fixed by fetching the content first. The corrected code now looks like this
$('.What').one('click',function() {
var content = $(this).text();
$(this).empty().html('<textarea name="X">' + content + '</textarea>');
$(this).find('textarea').focus();
});
See an example here: http://jsfiddle.net/xszUS/
Use:
$('.What').click(function() {
$(this).empty().html('<textarea name="X">' + $(this).text() + '</textarea>');
$(this).find('textarea').focus();
});
In short, use .focus()
not .select()
If you want to react to the user clicking/tabbing out of the textarea that is called blur
Try this
$('.What').click(function() {
var text = $(this).text();
$(this).empty().html('<textarea name="X">' + text + '</textarea>');
$(this).find('textarea').select();
$(this).unbind('click');
});
Checked it here: http://jsfiddle.net/Hy5ZB/
精彩评论