0

I have 2 buttons who throw a plain JS function (i dont want to use Jquery) but i'm asking what is the Best Practice between these methods :

function next() {
  var elements = document.getElementById('choices-multiple-remove-button');
  var param = [];
  for (var i = 0; i < elements.length; i++) {
    param.push(elements[i].value);
  }
  console.log(param);
}

function hello() {
  var elements = document.getElementById('choices-multiple-remove-button');
  var param = [];
  for (var i = 0; i < elements.length; i++) {
    param.push(elements[i].value);
  }
  console.log(param);
}
document.getElementById("workingbutton").addEventListener("click", hello);
<button id="next" class="btn btn-info" onclick="next()" type="button">Next</button>
<button id="workingbutton" class="btn btn-info" type="button">Next</button>
User863
  • 19,346
  • 2
  • 17
  • 41
Simon Delaunay
  • 145
  • 1
  • 18
  • 1
    You can find your question well explained here https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – pavelbere Apr 10 '19 at 13:11
  • "Best practice", particularly in the case of web dev, is often a heavily opinionated subject. If you don't have special needs (such as IE), pick whichever makes you feel the most comfortable and is the most suited to your use-case. – Kyll Apr 10 '19 at 13:11
  • I'd personally go with the "hello" one, so all the js stays in one place. Some people like to see in the html when something has a js handler on it, so I usually add attributes like "data-js-submit" and then use that as a selector in js – Jonas Grumann Apr 10 '19 at 13:11
  • People will say `addEventListener` is better – epascarello Apr 10 '19 at 13:12
  • @pavelbere, both your comments point to the same link. – Krishna Prashatt Apr 10 '19 at 13:14
  • @Krishna Prashatt that's because i commented and flagged XD – pavelbere Apr 10 '19 at 13:16

0 Answers0