我有一个包含多个字段的数据库搜索表单。其中两个,job_id
和 job_desc
,我想在使用另一个时将其禁用,反之亦然。我编写了一个小的 Javascript
函数来执行此操作。
这是我的表单代码:
<input type="text" id="job_id" oninput="input('job_id','job_desc')" onblur="blur('job_id','job_desc')">
<textarea id="job_desc" oninput="input('job_desc','job_id')" onblur="blur('job_desc','job_id')"></textarea>
这是我的 Javascript
代码:
function input(a,b)
{
var a = document.getElementById(a);
var b = document.getElementById(b);
alert("This will disable "+b); // Let the user know we are disabling the other field
b.value = ""; // Empty the other field
b.disabled = true; // Disable the other field
}
function blur(a,b)
{
var a = document.getElementById(a);
var b = document.getElementById(b);
if(a.value = "") // If the field is empty...
{
b.disabled = false; // Enable the other field.
}
}
我有这些问题:
1) 由于某种原因,一旦第一个字段为空且模糊,我的第二个字段就不会重新启用。这让我相信 onblur()
事件不起作用。
2)一旦我输入一些文本,我就会收到一次警报,一切都很好。但是,当我清空该字段并重新输入一些文本时,警报不会再次触发。如何重置 oninput()
事件?
这是我的 fiddle :fiddle
最佳答案
您可以使用“onkeyup”事件代替其他事件:
HTML 代码为:
<input id="job_id" onkeyup="input('job_id','job_desc')">
<br>
<textarea id="job_desc" onkeyup="input('job_desc','job_id')"></textarea>
还有 JS 函数:
function input(a, b) {
var ea = document.getElementById(a); // We put A in a variable
var eb = document.getElementById(b); // We put B in a variable
if(ea.value != ""){ // If the element have a value / text in it
if(!eb.disabled) // we check if the other element is disabled, if not, we trigger the alert
alert("This will disable " + b); // Let the user know we are disabling the other field
eb.value = ""; // Empty the other field
eb.disabled = true; // Disable the other field
}else{ // if the element's value is empty (which means that we have erased the existing value)
alert(b + " is now enabled"); // Let the user know we are enabling the other field
eb.disabled = false; // We re-enable the field
}
}
它在所有浏览器上都能正常工作.. 希望对您有帮助!
关于javascript - 首次使用后如何重置 oninput() html 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671903/