Dingo Dingo - 25 days ago 13
Javascript Question

Input event listener not firing for classes

I have a CSS class for 3 input boxes, called

.rgb
. In this
.rgb
class are three input boxes with ID's of:
#rgb
,
#rgb2
and
#rgb3
.

I am trying to capture when any of the three input boxes have text inputted using
.addEventListener
although it isn't working when I select the elements by class name. No innerHTML is being appended

Below is my minified code for this example:

document.getElementsByClassName('rgb').addEventListener("input", function() {
// Stores the r, g, b values
var r = document.getElementById('rgb').value;
var g = document.getElementById('rgb2').value;
var b = document.getElementById('rgb3').value;

document.getElementById('rgb-output').innerHTML = 'RGB: rgb(' + r + ', ' + g + ', ' + b + ')';
document.getElementById('hex-output').innerHTML = 'HEX: ' + rgbToHEX(r, g, b).toUpperCase();
}, false);


How can I modify the code so that it listens for input on all three input boxes under the
.rgb
class?

Answer

The result of getElementsByClassName is a node-list. You can't attach an event handler to a node list. You have to go into the node list and attach the handlers to the individual elements stored in that node list.

    var theInputs = document.querySelectorAll('.rgb')
    for(var i = 0; i < theInputs.length; ++i){
      theInputs[i].addEventListener("input", calc);
    }

    function calc() {
       // Stores the r, g, b values
       var r = document.getElementById('rgb').value;
       var g = document.getElementById('rgb2').value;
       var b = document.getElementById('rgb3').value;

       document.getElementById('rgb-output').innerHTML = 'RGB: rgb(' + r + ', ' + g + ', ' + b + ')';
       document.getElementById('hex-output').innerHTML = 'HEX: ' + rgbToHEX(r, g, b).toUpperCase();
    }

    function rgbToHEX(){ 
      return "it works!";
    }
<input class="rgb" id="rgb">
<input class="rgb" id="rgb2">
<input class="rgb" id="rgb3">

<div id="rgb-output"></div>
<div id="hex-output"></div>

Comments