FX1985 FX1985 - 3 months ago 43
Javascript Question

Trigger javascript function when any of multiple fields change (onchange)

I have a basic JS knowledge.

I need to trigger the function below when any of the fields change in a from. Here it works only when the var2 changes but I need it to be triggered when any of the var# will change. (I will have 30 var at the end in the form)

I think I need to have an OR condition, "if (var1.onchange OR var2.onchange OR ...) function()"

Thanks in advance for your valuable input!

<script>
window.onload = function () {
var var0 = document.getElementById('field09')
var1 = document.getElementById('field10')
var2 = document.getElementById('field11')
storage = document.getElementById('field12')

var2.onchange= function()


{
storage.value = var0.value+" ; "+var1.value+" ; "+var2.value;
};
};
</script>

Answer

Please try this:

<script>
window.onload = function () {
var var0 = document.getElementById('field09');
var var1 = document.getElementById('field10');
var var2 = document.getElementById('field11');
var storage = document.getElementById('field12');

var trigFunc = function()
{ 
    storage.value = var0.value+" ; "+var1.value+" ; "+var2.value;
};

var0.onchange = trigFunc ;
var1.onchange = trigFunc ;
var2.onchange = trigFunc ;

};
</script>

Demo: jsfiddle