I have 3 inputs, when I press enter on them same operations happend. This is my codeHow would you do this better?    var __this = this;    var a = document.getElementById(content).getElementsByTagName(more-content)[0].getElementsByTagName(input)[0];    var b = document.getElementById(content).getElementsByTagName(more-content)[1].getElementsByTagName(input)[0];    var b = document.getElementById(content).getElementsByTagName(more-content)[2].getElementsByTagName(input)[0];    a.onkeypress = function (e) {        if (e.which == 13) {            // do same stuff here        }    };    b.onkeypress = function (e) {        if (e.which == 13) {            // do same stuff here        }    };    b.onkeypress = function (e) {        if (e.which == 13) {            // do same stuff here        }    };
OnKeyPress event do same stuff on multiple inputs
javascript
There are in fact different ways to handle your request. Here's one I'd like to show as it is:re-useable (As you can use it on any element everywhere on the page multiple times.)decoupled from the HTML markup and from CSS classesHTMLAdd a data-*-attribute to the fields where the magic should happen:<input type=text name=a value=a data-log>JavaScriptquery those specific elementsattach the event handler to each elementrun your codeThe ES5 way:var logMe = document.querySelectorAll('[data-log]');for (var i = 0, max = logMe.length; i < max; i++) {    logMe[i].addEventListener('keypress', function(event) {        if (13 == event.which) {            console.log(this.value);        }    }, false);}Try it online.The ES6 way:let logMe = document.querySelectorAll('[data-log]');for (let item of logMe) {    item.addEventListener('keypress', function(event) {        if (13 == event.which) {            console.log(this.value);        }    }, false);}Try it online.That being said, you can alternatively use CSS classes as well to identify the elements:<input class=log type=text name=a value=a>And select the elements using:let logMe = document.getElementsByClassName('log');