david david - 5 months ago 16
Javascript Question

javascript: call function by classname

Trying to create a script that is bound by className and calls another function.

I have this code working for first instance of className, but if I remove the

[0]
in the first line of the script it no longer works.

<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 1" class="Bound"/>
<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 2" class="Bound"/>
<script>
inputBound = document.getElementsByClassName('Bound')[0];
inputBound.onfocus = function() {
var input = this.value;
formFunct(input);
}
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}
</script>


How do I get it to work for all inputs with
className="Bound"
? I do not need a jQuery solution.

Thank you.

Answer

Use a loop to iterate all elements.

Use Array#forEach, forEach() method executes a provided function once per array element.

Another alternate could to use Array.from over HTMLCollection returned by getElementsByClassName so that you can invoke Array# methods directly over returned result.

var inputBound = document.getElementsByClassName('Bound');
[].forEach.call(inputBound, function(inputBound) {
  inputBound.onfocus = function() {
    var input = this.value;
    formFunct(input);
  }
})

function formFunct(input) {
  console.log('done did the form Funct: ' + input)
}
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 1" class="Bound" />
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 2" class="Bound" />

Notes: