如何使用onkeyup在标签内显示用户输入值

How to display user input value inside label using onkeyup

我想知道如何使用 onkeyup 方法将在文本框中输入的值显示到标签中。 我可以在文本框中显示它。 这是我到目前为止所做的:

<script>
    function multiply(value){
        var x;
        x= 2*value;
        document.getElementById('out2x').value=x;
    }
</script>

<body>
  <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
    <label for="">Input</label>
    <input type="text" name="" onkeyup="multiply(this.value);">
    <br>

    <label for="">Result(x2):</label>
    <input type="text" id="out2x" name="" readonly>

  </div>

</body>

我尝试将 id 'out2x' 设置为标签,但它不起作用。

文档中的 script 实际上在哪里?它应该就在 CLOSING body 标记之前,以便在到达它时,所有 HTML 都将被解析。如果 script 在 HTML 被解析之前运行,您的 document.getElementById() 语句将找不到匹配的元素。

此外,inputvalue 始终是字符串。您必须将其转换为数字才能对其进行数学计算。有几种方法可以做到这一点,您需要为输入错误地包含非数字值的情况做好准备,但在下面,我通过在 + 前面加上 value 来转换它。

其他几件事....

您没有正确使用 label 元素。 for 属性的值必须与标签“用于”的表单元素的 id 属性值相匹配,或者您可以将表单元素嵌套在 label 中,以便它知道什么它涉及的元素。

不要使用内联 JavaScript - 将其分隔到 JavaScript 代码中。

<body>
  <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
    <label>Input
      <input type="text">
    </label>
    <br>

    <!-- Not always best to use an input for output. -->
    <span>Result(x2):
      <span id="out2x"></span>
    </span>

  </div>
  
  <!-- Place your script just before the closing body tag
       so that by the time it's reached, all the HTML elements
       will have been parsed. -->
  <script>
    // Do your event handling in JavaScript, not with inline JavaScript
    document.querySelector("input").addEventListener("keyup", function(event){
      // You must convert the input string to a number
      document.getElementById('out2x').textContent = 2* +this.value;
    });
  </script>
</body>

在你的案例中,我有一个像这样的 jQuery 的简单 Keyup

$('#value').keyup(function (){
    $('#copy-value').val($(this).val());
});

例如这个片段:

$('#value').keyup(function (){
    $('#copy-value').val($(this).val());
});
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
    <label for="">Input</label>
    <input id="value" type="text" name="">
    <br>
    <label for="">Result(x2):</label>
    <input id="copy-value" type="text" name="" readonly>

  </div>

</body>