2

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>
user1950349
  • 3,822
  • 15
  • 47
  • 87

3 Answers3

1

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;
}
msynk
  • 21
  • 3
  • Thanks Saleh, this work fine for delete. But after I delete something, I am not able to add anything back from textbox to textarea? Any thoughts why? – user1950349 Sep 06 '15 at 07:01
  • it seems using textContent is the problem. use value property instead in this line: document.getElementById('output').textContent += nameValue + '\n'; change it to: document.getElementById('output').value += nameValue + '\n'; – msynk Sep 06 '15 at 07:12
  • cool, now that is working. I see one more issue, when there is only one `name=value` pair there in the textarea, then delete doesn't work on them? Any thoughts? – user1950349 Sep 06 '15 at 07:17
  • its because of '\n' character. it was added to remove the line the selected text is in. to solve the issue you can insert this line at the end of deleteText function, after the first replacement: textComponent.value = textComponent.value.replace(selectedText + '\n', ''); textComponent.value = textComponent.value.replace(selectedText, ''); – msynk Sep 06 '15 at 07:20
  • So at the end of deleteText function you should have 3 replacements: textComponent.value = textComponent.value.replace('\n' + selectedText, ''); textComponent.value = textComponent.value.replace(selectedText + '\n', ''); textComponent.value = textComponent.value.replace(selectedText, ''); – msynk Sep 06 '15 at 07:28
  • hmm, works ok but now I see something funny. Let's say I added these two pairs - `Name=Value` and `Name=Value123`. Now If select first row which is `Name=Value`, then if I click delete, only 123 is left in the text area? – user1950349 Sep 06 '15 at 07:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/88911/discussion-between-user1950349-and-saleh-yusefnejad). – user1950349 Sep 06 '15 at 07:42
  • There are many points in which you can improve this code. But for last issue you can remove the last replacement, the one without '\n' in it. – msynk Sep 06 '15 at 07:45
  • It will be easier if you use ` – Sergio Marron Sep 06 '15 at 08:00
  • @SergioMarron Yes that is much easier and delete works fine, then my Sorting button doesn't work. How can I fix those? I change the output to list in my button method but still it doesn't work. – user1950349 Sep 06 '15 at 08:10
1

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

Sergio Marron
  • 511
  • 3
  • 9
0

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.)

Damian Silva
  • 336
  • 3
  • 19