Stevenson Stevenson - 5 months ago 16
CSS Question

Javascript: Sorting user input chronologically

Hopefully, I am not over thinking this. How should I approach sorting user input chronologically, with the oldest movie being displayed first in a newly sorted list?

example:


1980 - The Empire Strikes back

1996 - Independence Day

1997 - Titanic

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>

<body>

<form>
Year: <br>
<input id="year" type="text"><br>
Movie:<br>
<input id="mName" name="MovieName" type="text"><br>
</form>
<br>
<button onclick="myFunction(list)" type="submit">Submit</button>

<div id="container">
<ul id="list">
</ul>
</div>
<script src="assets/js/main.js">

</script>
</body>
</html>


JS

function myFunction(list){
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}


var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}

Answer

Update the DOM after every insertion of the li Element.

  • Instead of inserting year and name as plain text, wrap it in span to be access using DOM-api(querySelector/All)

  • Use Array.from to create new Array instance from an array-like or iterable object

  • Sort the collection using Array#sort

  • Append the sorted array to the parent UL element in Array#forEach loop

function myFunction(list) {
  var text = "";
  var inputs = document.querySelectorAll("input[type=text]");
  for (var i = 0; i < inputs.length; i++) {
    text += '<span>' + inputs[i].value + '</span>';
  }
  var li = document.createElement("li");
  li.innerHTML = text;
  document.getElementById("list").appendChild(li);
  var liElemens = document.querySelectorAll('#container #list li');
  liElemens = Array.from(liElemens);
  liElemens.sort(function(a, b) {
    var aSpan = +a.children[0].textContent;
    var bSpan = +b.children[0].textContent;
    return aSpan > bSpan;
  });
  var parent = document.querySelector('#list');
  parent.innerHTML = '';
  liElemens.forEach(function(elem) {
    parent.appendChild(elem);
  });
}
<form>
  Year:
  <br>
  <input id="year" type="text">
  <br>Movie:
  <br>
  <input id="mName" name="MovieName" type="text">
  <br>
</form>
<br>
<button onclick="myFunction(list)" type="submit">Submit</button>

<div id="container">
  <ul id="list">
  </ul>
</div>