My HTML Page has 10 Text Fields.
Currently no onChange EVENT is available for all ten fields.
<input type="text" name="text1" value="1">
<input type="text" name="text2" value="2">
<input type="text" name="text3" value="3">
<input type="text" name="text4" value="">
<input type="text" name="text5" value="">
<input type="text" name="text6" value="">...
Now, I want to add onChange Function in all fields whose field is of input
type.
How do I add onChange or onBlur even in my JS section?
In onChange function, I will call ajax function which will validate whether the field has Hacking Keywords.
So my question is:
How do I add onChange function for all form fields. My field should dynamically be like below:
<input type="text" name="text1" value="1" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text2" value="2" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text3" value="3" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text4" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text5" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text6" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text7" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
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);
}
function onChangeHandler() {
// Do something...
}
function onFocusHandler() {
if (this.value === prompt) {
this.value = '';
}
}
function onBlurHandler() {
if (this.value === '') {
this.value = prompt;
}
}
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>')
});
Demo1
Demo2
[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});
getElementsByTagname()
gets you an array of all input. Interate over them and addEventListener.
Or use jQuery's $('input').on('change'...)
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
}
}