我的 HTML 页面有 10 个文本字段。
目前所有十个字段都没有可用的 onChange EVENT。
<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="">...
现在,我想在所有字段为
input
类型的字段中添加 onChange 函数。
如何在我的 JS 部分添加 onChange 或 onBlur?
在 onChange 函数中,我将调用 ajax 函数,该函数将验证该字段是否具有 Hacking keywords。
所以我的问题是:
如何为所有表单字段添加 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 占位符的简单循环。 <<演示>>
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;
}
}
[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});
getElementsByTagname()
为您提供所有输入的数组。对它们进行交互并添加EventListener。
或者使用 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
}
}
如果您的
<input>
在表单中,您可以将 onchange 事件处理程序分配给表单本身。当焦点移开后,任何元素发生变化时都会触发。
尽管您可能需要一个
input
事件处理程序。例如,要在表单中的任何输入发生更改时启用“保存”按钮,您可以执行以下操作:
document.querySelector('form').addEventListener('input', event => {
document.querySelector('form button').removeAttribute('disabled');
document.querySelector('form button').textContent = 'Save';
});
<form>
<input type="text">
<input type="number" min="0">
<button type="submit" disabled>Input something...</button>
</form>