2014-10-31 77 views
0

我有一个数据库搜索表单与多个字段。其中两个,job_idjob_desc,我希望在使用另一个时禁用,反之亦然。我写了一个小的Javascript函数来做到这一点。如何在首次使用后重置oninput()html事件?

这里是我的表单代码:

<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

+1

仅供参考,并不在拨弄工作,因为你应该更改设置为“无包装 - 在”(现在你'的ReferenceError:输入没有defined'因为脚本是在onload上执行的)。 – pawel 2014-10-31 10:19:53

回答

2

您可以使用 “的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 
     } 
    } 

它可以在所有的浏览器上正常工作.. 我希望它能帮助你!

+0

我们如何才能做到这一点,警报不会触发每个字符输入? – 2014-10-31 10:16:44

+0

请检查答案的编辑 – 2014-10-31 10:34:53

+0

这不是我想到的,但它工作的很好,这才是真正重要的。最后一件事,请您补充一些意见,以便我了解问题是如何解决的? – 2014-10-31 10:41:01

1

除了提供的解决方案,您的代码无法正常工作的原因是它与native blur() function on the window object冲突,因此您的blur调用正在调用该函数,而不是您自己的blur函数。你需要改变它的名字。

另一个问题,一旦你解决这个问题是在

if(a.value = "") // If the field is empty... 

它应该有两个=迹象比较。

if(a.value == "") // If the field is empty... 

演示在http://jsfiddle.net/q11m3ahz/6/

相关问题