在按钮单击时从输入字段替换所选文本

时间:2016-09-08 11:17:38

标签: javascript jquery google-chrome firefox

我只是尝试用输入字段替换所选文本,例如从textarea替换另一个文本。 例如。如果我在输入字段中选择文本的一部分并单击按钮CENTER,则所选文本应包含在<center></center>中。

我从2009年发现这个“solution”似乎已经过时,我在Chrome和Firefox上尝试过,我得到的信息是我的浏览器不受支持。

还有另一种方法可以达到这个目的吗?它应该至少适用于Firefox和Chrome。

Textarea

enter image description here

3 个答案:

答案 0 :(得分:4)

试试这个:

function getSel() // javascript
{
console.log("test");

    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;

    // obtain the selected text
    var sel = allText.substring(start, finish);
    //append te text;
    var newText=allText.substring(0, start)+"<center>"+sel+"</center>"+allText.substring(finish, allText.length);

    console.log(newText);

    txtarea.value=newText;
}

https://jsfiddle.net/qpw1eemr/1/

答案 1 :(得分:1)

这是一个简单的例子

$(function() {
  $('textarea').select(function(event) {
    var elem = $(this);
    var start = elem.prop("selectionStart");
    var end = elem.prop("selectionEnd");
    
    var prefixStr = elem.text().substring(0, start);
    var sufixStr = elem.text().substring(end, elem.text().length);
    var selectedStr = elem.text().substring(start, end);
    
    function transform(str) {
      return '<center>' + str + '</center>'
    }
    
    elem.text(prefixStr + transform(selectedStr) + sufixStr);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea>iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</textarea>

答案 2 :(得分:0)

    // hope this would be usefull
    // i used these codes for auto completing the texts in textarea.
    // other methods change all matching items before the selected text
    // but this affects only the text where caret on.
    // at first, i divided textarea.value into 3 pieces. these are ;
    // p1; until the 'searched' item, p2 after 'searched' item
    // and pa = new item that will replaced with 'searched' item
    // then, i combined them together again.

    var tea = document.getElementById(targetTextArea);

    caretPosition = tea.selectionStart - ara.length; //ara=searched item
    p1 = tea.value.substring(0,caretPosition);
        console.log('p1 text : ' + p1);
    p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
        console.log('p2 text : ' + p2);
    pa = yeni;  //new item
        console.log('pa text : ' + pa);

    tea.value = p1 + pa + p2;

    tea.selectionStart = caretPosition + yeni.length;
    tea.selectionEnd = caretPosition + yeni.length;

    tea.focus();