将两个JavaScripts放在一起以复制输入

时间:2017-07-22 11:02:10

标签: javascript

有人可以帮我把这两个JavaScripts放在一起吗?

控制台正在从这两个内联文件向我发送错误。

    <script type="text/javascript">
    var 
    first = document.getElementById('jform_username'),
    second = document.getElementById('jform_email1'),
    third = document.getElementById('jform_email2');

    first.onkeyup = function () {
      second.value = first.value;
      third.value = first.value;
    };     
    </script>

    <script type="text/javascript">
    var 
    firstp = document.getElementById('jform_password1'),
    secondp = document.getElementById('jform_password2');

    firstp.onkeyup = function () {
      secondp.value = firstp.value;
    };     
    </script>

如果您还可以解释为什么这两者会产生错误的错误。

我认为它与功能有关,但我不知道。

这是实际问题的图片。

enter image description here

这是基于@Shubham Singla解决方案的新问题

enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:1)

问题是你在文件准备好之前尝试.getElementById&#34;。

使用以下代码等待文档准备就绪&#34;在你获得元素之前。

document.addEventListener("DOMContentLoaded", function(event) {
  //content here
});

检查以下代码段:

&#13;
&#13;
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) { 
  var 
    first = document.getElementById('jform_username'),
    second = document.getElementById('jform_email1'),
    third = document.getElementById('jform_email2');

    first.onkeyup = function () {
      second.value = first.value;
      third.value = first.value;
    };     
    
    var 
    firstp = document.getElementById('jform_password1'),
    secondp = document.getElementById('jform_password2');

    firstp.onkeyup = function () {
      secondp.value = firstp.value;
    };     
});
</script>

<input type="text" id="jform_username" />
<input type="text" id="jform_email1" />
<input type="text" id="jform_email2" />
<input type="text" id="jform_password1" />
<input type="text" id="jform_password2" />
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将keyup更改为firstp.addEventListener(&#34; keyup&#34;,function()...

<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var 
first = document.getElementById('jform_username'),
second = document.getElementById('jform_email1'),
third = document.getElementById('jform_email2');

first.addEventListener("keyup",function () {
  second.value = first.value;
  third.value = first.value;
});     

var 
firstp = document.getElementById('jform_password1'),
secondp = document.getElementById('jform_password2');

firstp.addEventListener("keyup",function () {
  secondp.value = firstp.value;
});   
});  
</script>

这是对其他答案的补充。所以用它更新了代码。