【问题标题】:Having one input field auto update another, and vice versa (probably using JavaScript)让一个输入字段自动更新另一个,反之亦然(可能使用 JavaScript)
【发布时间】:2012-01-05 06:10:14
【问题描述】:

我在 JavaScript 方面没有那么丰富的经验,所以需要一些项目方面的帮助。

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

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

【问题讨论】:

  • 这可以使用 javascript 完成,但如果您想使用 jquery 可以更轻松地完成

标签: javascript forms input


【解决方案1】:

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);

【讨论】:

    【解决方案2】:

    你可以为此编写一个 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

    【讨论】:

    • 是的,您可以在 html 页面中的每个位置编写 js,只需将其包含在
    • 我的意思是内联事件绑定。这不是语义代码。这是有效的顺便说一句
    • 非常低效的代码,我认为你需要一个 .value
    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 2018-11-30
    • 2022-11-04
    • 1970-01-01
    • 2018-03-20
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多