简体   繁体   English

从 textarea 中删除选定的文本

[英]delete selected text from textarea

I have an html page in which I have a textbox (Type your text) and TextArea list.我有一个 html 页面,其中有一个文本框(键入您的文本)和 TextArea 列表。 I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list.我需要在文本框中键入内容,然后单击“添加”按钮,以便文本框中的任何内容进入我的 TextArea 列表。 I need to type in this below format in the textbox.我需要在文本框中输入以下格式。

Name=Value

This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox.用户将使用此文本框将名称值对快速添加到该文本框正下方的列表中。 let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as假设我们在上面的文本框中输入Hello=World并单击添加,那么在下面的列表中,它应该显示为

Hello=World

And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.如果我们再次在同一个文本框中输入ABC=PQR ,那么在下面的列表中,它应该像这样显示,这意味着它应该继续在其原始条目下方添加新的名称值对。

Hello=World
ABC=PQR

But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format.但是如果语法不正确,比如它不在 Name=Value 对中,那么它不应该向列表添加任何内容,而是显示一个错误输入格式的弹出窗口。 Names and Values can contain only alpha-numeric characters.名称和值只能包含字母数字字符。 I also have two more buttons Sort by name and Sort by value .我还有两个按钮Sort by nameSort by value Once I click either of these two buttons, then it should sort entries in TextArea list using either name or value.单击这两个按钮中的任何一个后,它应该使用名称或值对 TextArea 列表中的条目进行排序。 Now I have all above things working fine without any issues.现在我上面的所有东西都可以正常工作,没有任何问题。

I have added another button called Delete .我添加了另一个名为Delete按钮。 Basically, when the Delete button is pressed all selected items in the listbox should be deleted.基本上,当按下Delete按钮时,列表框中的所有选定项目都应该被删除。 How can I add this feature?如何添加此功能? I am not able to understand this.我无法理解这一点。

Here is my jsfiddle .这是我的jsfiddle I need to use plain HTML and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning.我需要使用纯 HTML 和 Javascript,我还不想使用任何库,因为我想保持简单,因为我还在学习。

Below is my code:下面是我的代码:

<!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>

You can use something like this code:您可以使用以下代码:

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;
}

It will be easier if you use <select> instead of <texarea> and add your value/name pairs as <option> .如果您使用<select>而不是<texarea>并将您的值/名称对添加为<option>会更容易。 Hope this can help you希望可以帮助你

I would reccomend the use of an array.我会推荐使用数组。 In this method, you could run a function that stores the value of "textbox" in an array (then clears the field).在此方法中,您可以运行一个函数,将“文本框”的值存储在一个数组中(然后清除该字段)。 EX:前任:

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

Now that you have the 'commands' stored, you can utilize a for loop to print the contents of the array either directly to the textarea, or avoid the loop and print the array to a string, then print the string in the textarea.现在您已经存储了“命令”,您可以使用 for 循环将数组的内容直接打印到 textarea,或者避免循环并将数组打印为字符串,然后在 textarea 中打印字符串。 (Note: Using an array may be more helpful if you will need to edit/change/delete the separate prompts in the future.) (注意:如果您将来需要编辑/更改/删除单独的提示,则使用数组可能会更有帮助。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM