javascript - 首次使用后如何重置 oninput() html 事件?

标签 javascript html

我有一个包含多个字段的数据库搜索表单。其中两个,job_idjob_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/

相关文章:

javascript - 每个单元格具有不同颜色的图表

javascript - 在 JavaScript 中使用父容器包装多个元素的最简单方法

javascript - MobX Store 变量赋值

javascript - 如何获取使用 twitter bootstrap 创建的按钮的值?

javascript - 如果 src 是 http ://without link,则隐藏 iframe

javascript - 通量和 WebSocket

javascript - SpeechSynthesis API onend 回调不起作用

Javascript 代码在 Mozilla 的同一页面上提交表单

html - Django : Could not parse the remainder: '{{' from '{{

javascript - 使用popcornjs,如何一键播放视频并显示脚注?