【问题标题】:Dynamically change value of form in JS在 JS 中动态改变表单的值
【发布时间】:2014-12-31 00:02:40
【问题描述】:

Here 是 jsFiddle 的一个示例。我有两个字段.. opp3 和 opp4。用户可以修改 opp4 中的文本,但我希望 opp3 中的文本在用户更改 opp4 中的文本时动态更改。

我看到了 this 动态更改文本的解决方案,但我不能完全使用它,因为我正在创建一个greasemonkey 脚本(并且无法编辑 html,只能添加 JS)并且我只想更改领域的一部分,而不是全部。

HTML:

<input id="opp3" maxlength="120" name="opp3" size="40" tabindex="1" type="text" style="cursor: auto; background-attachment: scroll; background-position: 100% 50%; background-repeat: no-repeat;" readonly>

<br><br>

<input autocomplete="off" id="opp4" maxlength="255" name="opp4" onchange="getElementByIdCS('opp4_lkid').value='';getElementByIdCS('opp4_mod').value='1';" size="40" tabindex="2" type="text">

JS:

document.getElementById('opp3').value = "Text <VALUE FROM OPP4> More Text";
document.getElementById('opp4').value = "Field Text Here";

【问题讨论】:

    标签: javascript greasemonkey


    【解决方案1】:

    您可以在 opp4 输入上使用事件侦听器来实现此目的。

    var opp3 = document.getElementById('opp3')
    opp3.value = "Text <VALUE FROM OPP4> More Text";
    var opp4 = document.getElementById('opp4')
    opp4.value = "Field Text Here";
    
    opp4.addEventListener('input', function () {
        opp3.value = this.value;
    });
    <input id="opp3" maxlength="120" name="opp3" size="40" tabindex="1" type="text" style="cursor: auto; background-attachment: scroll; background-position: 100% 50%; background-repeat: no-repeat;" readonly>
        
       <br><br>
           
           <input autocomplete="off" id="opp4" maxlength="255" name="opp4" size="40" tabindex="2" type="text">

    【讨论】:

    • 完美!我修改了 opp3.value,所以它将我想要的文本与 this.value 连接起来。
    【解决方案2】:

    你可以完成一个相似的结果减去一个事件监听器,如下:

    var inputs = document.getElementsByTagName('input');
    var opp4 =   document.getElementById('opp4');
    opp4.value = "Field Text Here";
    
    var opp3 = document.getElementById('opp3');
    opp3.value = "Text <VALUE FROM OPP4> More Text";  
    inputs[1].onchange = function(){ 
              opp3.value = opp4.value;
              };
    

    查看演示here

    诚然,使用事件监听器会更酷一些,因为更改是同时发生的。我喜欢这种效果,但用户呢?他们会觉得这很有趣还是令人不安的分心?我的解决方案表现出与http://jsfiddle.net/4PAKE/http://jsfiddle.net/4PAKE/提出问题的人所喜欢的相同的动态行为

    【讨论】:

    • 问题是onchange 只在模糊时触发。您不会同时看到两个输入的变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多