w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
JavaScript Taking in values from text box store into an array create new array to sort

A bit modified original code

HTML

<h1>ToDo List - Date: <span
id='today'>&nbsp;</span></h1>
    <div id="todolist">
        <p><input type="button" id="additem" value="Add Item"
/></p>
    </div>
<hr>

<div>
    <p><input type="button" id="sortitems" value="Sort and Display
Items" /></p>
    <p id="displayitems"></p>
</div>

Javascript

var sortItem = function(){
    var myClassTag = document.getElementsByClassName("listitem");
    //convert nodelist ot array
    myClassTag     = Array.prototype.slice.call(myClassTag, 0);
    //let the sort function sort it for you
    myClassTag.sort(function(a, b){
        return a.value > b.value ? 1 : -1;
    });

    var myToDoList = document.getElementById('todolist');
    //update items position
    update(myToDoList, myClassTag);
}
//update items position, reappending will do the job
function update(target, listOfItems){
    for(var i = 0; i < listOfItems.length; i++){
        target.appendChild(listOfItems[i]);
    }
}

var addItem = function(){
     var myToDoList = document.getElementById('todolist');
     var myInput    = document.createElement("input");

     myInput.setAttribute("type", "text");
     myInput.setAttribute("class", "listitem");
     myToDoList.appendChild(myInput);

     var myBr = document.createElement("br");
     myToDoList.appendChild(myBr);
}

window.onload = function(){
     document.getElementById('additem').addEventListener('click', addItem);
     document.getElementById('sortitems').addEventListener('click',
sortItem);
}

UPD You can modify update function, to make it works as you wanted, ex:

for(var i = 0; i < listOfItems.length; i++){
    var child = document.createElement('span');
    child.innerText = listOfItems[i].value;
    target.appendChild(child);
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.