Why isn't this code working?
http://sandbox.phpcode.eu/g/5db40.php
<form>
<textarea></textarea>
</form>
<script>
$(function(){
$("textarea").keydown(function(e){
if (e.keyCode == 9)开发者_StackOverflow中文版{
$("textarea").selectionStart.append(" ");
e.preventDefault();
}
});
});
</script>
You have to press TAB on textarea
Problem is that it doesn't do/append four spaces and it does default browser action (switch to adress tab in Chrome)
Thoughts?
Related to this question, try:
$(function () {
$("textarea").keydown(function (e) {
if (e.keyCode == 9) {
e.preventDefault();
var $this = $(this);
var pos = $this[0].selectionStart;
$this.val($this.val().substring(0, pos) + " " + $this.val().substring(pos));
$this.setCursorPosition(pos + 4);
}
});
});
And add the JQuery from this post.
new function($) {
$.fn.setCursorPosition = function(pos) {
if ($(this).get(0).setSelectionRange) {
$(this).get(0).setSelectionRange(pos, pos);
} else if ($(this).get(0).createTextRange) {
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
For manipulating textarea selections and caret positions in jQuery, I recommend using my jQuery plug-in for doing this, which work in all major browsers and provides methods for getting and setting the caret/selection position, inserting content at the caret position and more. The code you want would be:
$("textarea").keydown(function(e) {
if (e.keyCode == 9) {
e.preventDefault();
$(this).replaceSelectedText(" ");
}
});
Take a look at Keypress in jQuery: Press TAB inside TEXTAREA (when editing an existing text)
Try this one, i'm damn sure it will work.
<form>
<textarea></textarea>
</form>
<script>
$(function(){
$("textarea").keydown(function(e){
if (e.which == 9){
$("textarea").append(" ");
return false;
}
});
});
</script>
I just simply changed the word "keyCode" to "which", 'cause the word keyCode is derived from jquery ui.
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
This (JSFiddle) was the best I could manage, but I can't get it working on Firefox or Chrome. If somebody manages to get the button press select text in textarea with Chrome working, feel free to let me know.
精彩评论