user1950349
user1950349

Reputation: 5146

delete selected text from textarea

I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. 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

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.

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. Names and Values can contain only alpha-numeric characters. I also have two more buttons Sort by name and Sort by value. Once I click either of these two buttons, then it should sort entries in TextArea list using either name or value. Now I have all above things working fine without any issues.

I have added another button called Delete. Basically, when the Delete button is pressed all selected items in the listbox should be deleted. How can I add this feature? I am not able to understand this.

Here is my 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.

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>

Upvotes: 2

Views: 3881

Answers (3)

Sergio Marron
Sergio Marron

Reputation: 521

It will be easier if you use <select> instead of <texarea> and add your value/name pairs as <option>. Hope this can help you

Upvotes: 1

Saleh Yusefnejad
Saleh Yusefnejad

Reputation: 21

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

Upvotes: 1

Damian Silva
Damian Silva

Reputation: 336

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. (Note: Using an array may be more helpful if you will need to edit/change/delete the separate prompts in the future.)

Upvotes: 0

Related Questions