How To Add Onchange Function For All Html Form Fields
My HTML Page has 10 Text Fields. Currently no onChange EVENT is available for all ten fields.
Solution 1:
This can be achieved with vanilla JavaScript as zvona suggests.
Here is a simple loop to mock an HTML5 placeholder. <<DEMO>>
var prompt = 'Type something here';
var textFields = document.querySelectorAll('input[name^="text"]');
var index = 0;
for (index = 0; index < textFields.length; ++index) {
var textField = textFields[index];
textField.addEventListener('change', onChangeHandler);
textField.addEventListener('focus', onFocusHandler);
textField.addEventListener('blur', onBlurHandler);
textField.value = prompt;
console.log(textField);
}
functiononChangeHandler() {
// Do something...
}
functiononFocusHandler() {
if (this.value === prompt) {
this.value = '';
}
}
functiononBlurHandler() {
if (this.value === '') {
this.value = prompt;
}
}
Solution 2:
you can try to give change function to your form using
$('.form :input').change(function(e){
$('#log').prepend('<p>Form changed ' + $(e.target).attr('id') + '</p>')
});
Solution 3:
[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});
Solution 4:
getElementsByTagname()
gets you an array of all input. Interate over them and addEventListener.
Or use jQuery's $('input').on('change'...)
Solution 5:
Try something like:
var inputList = document.getElementsByTagName("input");
for(var i=0;i<inputList.length;i++){
inputList[i].onchange = function(){
//function here
}
inputList[i].onblur = function(){
//function here
}
}
Post a Comment for "How To Add Onchange Function For All Html Form Fields"