Firing an input event only when the field has a value
So, with this one I want to only react to the event when the field has changed (the standard input event) but NOT when it has been changed to become empty.
by Matt Rummler
HTML
<div id="overarchingDiv">
<form id="testForm0">
<input type="text" id="field1">
</form>
<form id="testForm1">
<input type="text" id="field1" class='theOneField'>
</form>
<form id="testForm2">
<input type="text" id="field1">
</form>
<button id="populate fields button" class='thatOneButton'>
Populate All Fields
</button>
</div>
JavaScript
var topLevel = document.getElementById('overarchingDiv');
var finalField = topLevel.getElementsByClassName('theOneField')[0];
var buttonOne = topLevel.getElementsByClassName('thatOneButton')[0];
finalField.addEventListener("input", function(e){showAlert(e,finalField);}, false);
buttonOne.addEventListener("click", function(e){populateOneOrMoreFields(e);}, false);
//// SUPPORTING FUNCTION ////
Object.forEach=(function forEach()
{
return function(obj,fn)
{
if(obj.length)
{
for (var i = 0, ol = obj.length, v = obj[0]; i < ol && fn(v, i) !== false; v = obj[++i]);
}
else
{
for (var p in obj) if (fn(obj[p], p) === false) break;
}
};
})(this);
//// primary function(s) ////
function populateOneOrMoreFields(event,inputValue)
{
inputValue=inputValue || 1;
var inputEvent = new Event('input');//,{bubbles:false,cancelable:false});
var inputElementsCollection = document.getElementsByTagName('input');
// var inputElementEventTarget=document.getElementById('');
Object.forEach(inputElementsCollection, function(inputElement, key)
{
inputElement.value=inputValue;
// alert('The class of the current element is: '+inputElement.className);
if(inputElement.className=='theOneField')
{
inputElement.dispatchEvent(inputEvent);
}
// alert('The new value of the current element is: '+inputElement.value);
});
}
function showAlert(e,fieldOne)
{
if(fieldOne.value)
{
alert("Event is called because the input changed! The following is the type of event: " + e.type);
}
}