让一个输入字段自动更新另一个,反之亦然(可能使用JavaScript)

时间:2012-01-05 06:10:14

标签: javascript forms input

我不是那种经验丰富的JavaScript,所以需要帮助项目。

我有一种形式的,其中包括3个输入文本字段(让我们称之为A,B和C)。我需要用户只能输入A + B OR C.因此,一旦用户点击另一个(反之亦然),就可以使表单字段处于非活动状态。

非常感谢任何帮助。我的猜测是需要在JavaScript中完成。

2 个答案:

答案 0 :(得分:0)

您可以为此编写一个javascript,其绑定如下

<script>
function fun(ele){
var elea=document.getElementById('a');
var eleb=document.getElementById('b');
var elec=document.getElementById('c');
if (ele.id='a' &&(eleb.length==0 || elec.length==0))
{
      this.readonly=false;
}
if (ele.id='b' && (elea.length==0 || elec.length==0))
{
       this.readonly=false;
}
if (ele.id='c' && (elea.length==0 || eleb.length==0))
{
       this.readonly=false;
}

}
</script>
<input type="text" id="a" onfocus="fun(this)" readonly="true"/>
<input type="text" id="b" onfocus="fun(this)" readonly="true"/>
<input type="text" id="c" onfocus="fun(this)" readonly="true"/>

您还可以动态绑定事件,而不是内联,请参阅Four Ways Javascript Binding Event Listeners

答案 1 :(得分:0)

HTML

<input class="onlyone" id="first" />
<input class="onlyone" id="second" />
<input class="onlyone" id="third" />

的JavaScript

document.querySelectorAll('.onlyone').addEventListener('click', function(){
if(this.getAttribute('disabled') != 'disabled'){ // check if it was disabled before

   for(var i=0; i<document.querySelectorAll('.onlyone').length; i++){
    document.querySelectorAll('.onlyone')[i].setAttribute('disabled, 'disabled'); //disable em all
   }

   this.removeAttribute('disabled'); //enable this one
}
}, false);
相关问题