【问题标题】:Add Tags to Textarea by click on Tags respectively通过分别单击标签将标签添加到文本区域
【发布时间】:2013-10-29 12:08:52
【问题描述】:

我正在开发这个 small Js Module,其中有一个标签列表:

例如:用户名、电子邮件等

当我点击 Username 时,它应该会在 textarea 中自动输入 [USERNAME]。我已经尝试过并且工作正常。

这里是Fiddle

现在的问题是当我添加标签时,它总是添加在文本的末尾。

看看这个字符串:嗨 [USERNAME] ,这是你的 ['EMAIL']。

现在,如果我忘记选择 [USERNAME] 并输入:嗨,这是您的 ['EMAIL']。

所以现在如果我在 Hi 之后单击然后选择 用户名标签,它将在末尾添加标签而不是在“Hi”之后添加它

我该如何解决这个问题?

这是我的代码:

JS:

$('.tags').click(function (){
    var currentTag = $(this).attr("id");
    var currentTxt = $('#description').val();

    $('#description').val(currentTxt+currentTag);   
});

HTML:

<table width="300" border="0" cellspacing="8" cellpadding="0">
  <tr>
    <td>Tags: <a href="javascript:void(0);" class="tags" id="[USERNAME]">USERNAME</a> , <a href="javascript:void(0);" class="tags" id="[EMAIL]">EMAIL</a></td>
  </tr>
  <tr>
    <td>
    <textarea name="description" id="description" cols="45" rows="5"></textarea></td>
  </tr>
</table>

你也可以在这里查看我的 DEMO:http://jsfiddle.net/kyfa2/1/

用非常简单的话:在 textarea 中输入这句话:

              Hi , this is your Email

现在点击你好,然后点击用户名标签。

我想要这样:

Hi [USERNAME] , this is your Email.

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    使用下面的功能,如果有的话更新我!

      var $textBox;
    
     $(document).ready(function() {
    
            $('.tags').click(function (){
            var currentTag = ' ' +$(this).attr("id")+' ';
            var currentTxt = $('#description').val();
           insertText(currentTag);
    
    
        });    
            $textBox = $("#description");
    
            function saveSelection(){
                textBox.data("lastSelection", $textBox.getSelection());
            }
    
            $textBox.focusout(saveSelection);
    
            $textBox.bind("beforedeactivate", function() {
                saveSelection();
                $textBox.unbind("focusout");
            });
        });
    
        function insertText(text) {
            var selection = $textBox.data("lastSelection");
            $textBox.focus();
            $textBox.setSelection(selection.start, selection.end);
            $textBox.replaceSelectedText(text);
        }
    

    demo:http://jsfiddle.net/rQXrJ/121/

    来源和解释:Insert value into TEXTAREA where cursor was

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多