user1950349
user1950349

Reputation: 5146

not able to sort entries in textarea basis on key and value both using javascript?

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. Now I have all above things working fine without any issues.

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. Is this possible to do using Javascript? I tried adding two methods sortByKey and sortByValue as I am using split, sort and join methods but its not working as expected and something is getting messed up.

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. What wrong I am doing here?

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.key.split("=").sort().join("\n");
    }

    document.getElementById('sortbyvalue').onclick = sortByValue;
    function sortByValue() {
        var textarea = document.getElementById("output");
        textarea.value = textarea.value.split("=").sort().join("\n");
    }
</script>

</head>

<body>
<h3>Test</h3>

<label for="pair">Name/Value Pair</label></br>
<div class="form-section">
    <div class="fleft">
        <input type='text' id='my-text-box' value="Name=Value" />
    </div>
    <div class="fright">
        <button type="button" id='add' onclick='addtext()'>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: 0

Views: 626

Answers (2)

Julien Gr&#233;goire
Julien Gr&#233;goire

Reputation: 17144

You need to split your textarea by lines and then split each line to be able to compare either name or value. Right now, you're only splitting once.

So the sequence should be:

  • split your lines in an array - you only need to replace ('=') with ('\n').
  • for each line you compare either the name or the value - these can be done in sort. Sort will already go through your line array and allows you to define which element you want to compare.

You can do it like this:

function sortByKey() {
    var textarea = document.getElementById("output");
    textarea.value = textarea.value.split("\n").sort(function(a, b){
        if(a != "" && b != ""){//this because you have empty lines to handle
            return a.split('=')[0].localeCompare(b.split('=')[0])
        } else {
            return 0
        }
    }).join("\n");
}

https://jsfiddle.net/56hs2nmn/

To sort by value, you simply use a.split('=')[1].localeCompare(b.split('=')[1]).

You'll see that sort by value and by key is almost exactly the same, you should try to optimize by having only one function for both. And also clarify the steps by using variables instead of throwing it all in one line. But it should put you in the right direction.

Upvotes: 1

Daniel Lizik
Daniel Lizik

Reputation: 3144

This could work

https://jsfiddle.net/68cp72s6/

(function() {
    "use strict";

    var dom = getDom(["user", "output", "add", "sortbykey", "sortbyvalue"], {});
    var rx = /[\w]+=[\w]+/;
    var model = [];

    function add() {
        var input = dom.user.value;
        if (!rx.test(input)) return;
        var split = input.split("=");
        var obj = { key: split[0], val: split[1] };
        model.push(obj);
        viewModel(model);
    }

    function viewModel(input) {
        var data = JSON.stringify(input, null, 2);
        dom.output.value = data;
    }

    function getDom(arr, tmp) {
        arr.forEach(function(s) {
            tmp[s] = document.getElementById(s);
        });
        return tmp;
    }

    function sorter(prop) {
        return function() {
            var sorted = model.sort(function(a, b) {
                if (a[prop] < b[prop]) return -1;
                if (a[prop] > b[prop]) return 1;
            });
            viewModel(sorted);            
        }
    }

    dom.add.addEventListener("click", add);  
    dom.sortbykey.addEventListener("click", sorter("key"));
    dom.sortbyvalue.addEventListener("click", sorter("val"));

})();

Upvotes: 1

Related Questions