Skip to content Skip to sidebar Skip to footer

Sorting Logic For Arranging A List

I have made some changes with sorting because previous logic was just comparing the current value with the first index value. I am trying to compare with all the values. Please go

Solution 1:

Loop through the array of child elements and compare each element and insertBefore or append the element

functionmyFunction() {
  var node = document.createElement("LI");
  var answer = document.getElementById("selectMe").value;
  var textboxvalue = document.getElementById("t1").value;
  if (answer == "positive") {
    var textnode = document.createTextNode(textboxvalue);
    node.appendChild(textnode);
    var p = document.getElementById("Positive").childNodes; // child Nodes of positiveif (p[1]) {
      for (var i = 0; i < p.length; i++) {
        alert(i);
        var preValue = p[i].innerHTML;
        if (preValue > textboxvalue) { // compare with previous positive value to insertbefore or appenddocument.getElementById("Positive").insertBefore(node, p[i]);
          break;
        } else {
          document.getElementById("Positive").appendChild(node);
        }
      }
    } else {
      document.getElementById("Positive").appendChild(node);
    }

  } elseif (answer == "negative") {
    var c = document.getElementById("negative").childNodes; // child Nodes of negativevar textnode = document.createTextNode(textboxvalue);
    node.appendChild(textnode);

    if (c[1]) {
      for (var i = 0; i < c.length; i++) {
        alert(i);
        var preValue = c[i].innerHTML;
        if (preValue > textboxvalue) { // compare with previous negative value to insertbefore or appenddocument.getElementById("negative").insertBefore(node, c[i]);
          break;
        } else {
          document.getElementById("negative").appendChild(node);
        }
      }
    } else {
      document.getElementById("negative").appendChild(node);
    }
  }

  //document.body.appendChild(node);
}

http://codepen.io/nagasai/pen/ZOLyWZ

Post a Comment for "Sorting Logic For Arranging A List"