我的HTML页中有10个文本字段。
目前没有OnChange事件可用于所有十个字段。
<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="">...
现在,我想添加的onChange功能在其领域是各个领域input
类型。
如何添加的onChange或者甚至的onblur在我的JS部分?
在功能的onChange,我会打电话给AJAX功能,将验证该字段是否有黑客关键词。
所以我的问题是:
如何添加的onChange功能适用于所有表单字段。 我场应该动态地象下面这样:
<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" >
这可以用香草JavaScript作为实现zvona建议。
下面是一个简单的循环来模拟一个HTML5占位符。 << 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;
}
}
你可以尝试使用找零功能,以您的形式
$('.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()
让你所有输入的数组。 Interate了他们的addEventListener。
或使用jQuery的$('input').on('change'...)
尝试是这样的:
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
}
}