smilies to textarea on click

余生颓废 提交于 2019-11-30 22:34:09

Also, you can use something this function:

function ins2pos(str, id) {
   var TextArea = document.getElementById(id);
   var val = TextArea.value;
   var before = val.substring(0, TextArea.selectionStart);
   var after = val.substring(TextArea.selectionEnd, val.length);
   TextArea.value = before + str + after;
}

For your example, look here.


UPD 1:

To set cursor at specified position, use the next function:

function setCursor(elem, pos) {
   if (elem.setSelectionRange) {
      elem.focus();
      elem.setSelectionRange(pos, pos);
   } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
   }
}

I updated code on jsFiddle, so, to view new example, look here.

Zoltan Toth

Try this - http://jsfiddle.net/JVDES/12/

Credit for the caret position function goes to - https://stackoverflow.com/a/1891567/981134

The difference between no wrap (head) and no wrap (body) is that the former will run the code as soon as possible and the latter will run the code after the page has loaded.

In this case, with no wrap (head), the code is being run before '#emoticons a' exists. Thus $('#emoticons a') returns none and does not attach the click handler. Later, the link is created.

Thus, the solution is to tell the code to run when the page is loaded.

There are a couple, equivalent ways of doing this. http://api.jquery.com/ready/

  1. $(document).ready(handler)

  2. $().ready(handler) (this is not recommended)

  3. $(handler)

So using version 3, we have:

$(function() {
    $('#emoticons a').click(function(){

    var smiley = $(this).attr('title');
    $('#description').val($('#description').val()+" "+smiley+" ");

    });
});

http://jsfiddle.net/Nc67C/

MaJac89

try also this...

$('#emoticons a').click(function() {

    var smiley = $(this).attr('title');

    var cursorIndex = $('#description').attr("selectionStart");
    var lStr =  $('#description').val().substr(0,cursorIndex);
    var rStr = $('#description').val().substr(cursorIndex);

    $('#description').val(lStr+" "+smiley+" "+rStr);

});

Fix after your comment:

$('#emoticons a').click(
function(){var smiley = $(this).attr('title');

var cursorIndex = $('#description').attr("selectionStart");
var lStr =  $('#description').val().substr(0,cursorIndex) + " " + smiley + " ";
var rStr = $('#description').val().substr(cursorIndex);

$('#description').val(lStr+rStr);
$('#description').attr("selectionStart",lStr.length);                                     
});​

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!