【问题标题】:delete selected text from textarea从 textarea 中删除选定的文本
【发布时间】:2015-12-01 22:44:26
【问题描述】:

我有一个 html 页面,其中有一个文本框(键入您的文本)和 TextArea 列表。我需要在文本框中输入内容,然后单击“添加”按钮,以便文本框中的任何内容都进入我的 TextArea 列表。我需要在文本框中输入以下格式。

Name=Value

用户将使用此文本框将名称值对快速添加到该文本框下方的列表中。假设我们在上面的文本框中输入Hello=World并点击添加,那么在下面的列表中,它应该显示为

Hello=World

如果我们再次在同一个文本框中输入ABC=PQR,那么在下面的列表中,它应该显示如下,这意味着它应该继续在其原始条目下方添加新的名称值对。

Hello=World
ABC=PQR

但是如果语法不正确,比如它不在 Name=Value 对中,那么它不应该向列表中添加任何内容,而是显示一个错误输入格式的弹出窗口。名称和值只能包含字母数字字符。我还有两个按钮Sort by nameSort by value。一旦我单击这两个按钮中的任何一个,它就会使用名称或值对 TextArea 列表中的条目进行排序。现在我上面的所有东西都可以正常工作,没有任何问题。

我添加了另一个名为Delete 的按钮。基本上,当按下Delete 按钮时,列表框中的所有选定项目都应被删除。如何添加此功能?我无法理解这一点。

这是我的jsfiddle。我需要使用纯 HTML 和 Javascript,我还不想使用任何库,因为我想保持简单,因为我还在学习。

下面是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>

<style type="text/css">
    #my-text-box {
        font-size: 18px;
        height: 1.5em;
        width: 585px;
    }
    textarea{
        width:585px;
        height:300px;
    }
    .form-section{
        overflow:hidden;
        width:700px;
    }
    .fleft{float:left}
    .fright{float:left; padding-left:15px;}
    .fright button{display:block; margin-bottom:10px;}
</style>

<script language="javascript" type="text/javascript">
    document.getElementById('add').onclick = addtext;
    function addtext() {
        var nameValue = document.getElementById('my-text-box').value;
        if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue))
            document.getElementById('output').textContent += nameValue + '\n';
        else
            alert('Incorrect Name Value pair format.');
    }

    document.getElementById('sortbykey').onclick = sortByKey;
    function sortByKey() {
        var textarea = document.getElementById("output");
        textarea.value = textarea.value.split("\n").sort(function(a, b){
            if(a != "" && b != ""){
                return a.split('=')[0].localeCompare(b.split('=')[0])
            } else {
                return 0
            }
        }).join("\n");
    }

    document.getElementById('sortbyvalue').onclick = sortByValue;
    function sortByValue() {
        var textarea = document.getElementById("output");
        textarea.value = textarea.value.split("\n").sort(function(a, b){
            if(a != "" && b != ""){
                return a.split('=')[1].localeCompare(b.split('=')[1])
            } else {
                return 0
            }
        }).join("\n");
    }
</script>

</head>

<body>
    <h3>Test</h3>
    <label for="pair">Type your text</label></br>
    <div class="form-section">
        <div class="fleft">
            <input type='text' id='my-text-box' value="Name=Value" />
        </div>
        <div class="fright">
            <button id='add' type="button">Add</button>
        </div>
    </div>
    </br>
    </br>
    </br>

    <label for="pairs">Name/Value Pair List</label></br>
    <div class="form-section">
        <div class="fleft">
           <textarea id='output'></textarea>
        </div>
        <div class="fright">
            <button type="button" id='sortbykey' onclick='sortByKey()'>Sort by name</button>
            <button type="button" id='sortbyvalue' onclick='sortByValue()'>Sort by value</button>
        </div>
    </div>

</body>
</html>

【问题讨论】:

标签: javascript html css


【解决方案1】:

如果您使用&lt;select&gt; 而不是&lt;texarea&gt; 并将值/名称对添加为&lt;option&gt; 会更容易。希望this能帮到你

【讨论】:

    【解决方案2】:

    你可以使用类似这样的代码:

    document.getElementById('btnDelete').onclick = deleteText;
    function deleteText() {
        var textComponent = document.getElementById('output'),
            selectedText = getSelectedText(textComponent);
        if (!selectedText) return;
        textComponent.value = textComponent.value.replace('\n' + selectedText, '');
    }
    
    // http://stackoverflow.com/questions/1058048/how-to-get-selected-text-inside-a-textarea-element-by-javascript
    function getSelectedText(textComponent)
    {
        var selectedText = '';
        if (document.selection != undefined) { // IE
            textComponent.focus();
            var sel = document.selection.createRange();
            selectedText = sel.text;
        } else if (textComponent.selectionStart != undefined) { // other browsers
            var startPos = textComponent.selectionStart;
            var endPos = textComponent.selectionEnd;
            selectedText = textComponent.value.substring(startPos, endPos)
        }
        return selectedText;
    }
    

    【讨论】:

    • 感谢 Saleh,这项工作可以删除。但是在我删除某些内容后,我无法将任何内容从文本框添加回文本区域?有什么想法吗?
    • 似乎使用 textContent 是问题所在。在此行中使用 value 属性: document.getElementById('output').textContent += nameValue + '\n';将其更改为: document.getElementById('output').value += nameValue + '\n';
    • 酷,现在可以了。我看到另一个问题,当文本区域中只有一对 name=value 时,删除对它们不起作用?有什么想法吗?
    • 它是因为 '\n' 字符。添加它是为了删除所选文本所在的行。要解决此问题,您可以在第一次替换后在 deleteText 函数的末尾插入此行: textComponent.value = textComponent.value.replace(selectedText + '\n' , ''); textComponent.value = textComponent.value.replace(selectedText, '');
    • 所以在 deleteText 函数结束时你应该有 3 个替换: textComponent.value = textComponent.value.replace('\n' + selectedText, ''); textComponent.value = textComponent.value.replace(selectedText + '\n', ''); textComponent.value = textComponent.value.replace(selectedText, '');
    【解决方案3】:

    我会推荐使用数组。在这种方法中,您可以运行一个函数,将“文本框”的值存储在一个数组中(然后清除该字段)。例如:

    var newText = document.forms[0].elements[0].value;
    //This retrieves and stores the value of 'textbox' into variable 'newText'.
    myArray[myArray.length] = newText 
    //This adds the value of 'newText' to an array named 'myArray'
    document.forms[0].elements[0].value = "";
    //This line is optional, it would clear the 'textbox', so you wouldn't have to clear it manually
    

    现在您已经存储了“命令”,您可以利用 for 循环将数组的内容直接打印到 textarea,或者避免循环并将数组打印为字符串,然后在文本区域。 (注意:如果您将来需要编辑/更改/删除单独的提示,使用数组可能会更有帮助。)

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多