【问题标题】:Text from one textbox to another using JavaScript使用 JavaScript 从一个文本框到另一个文本框的文本
【发布时间】:2023-03-16 21:24:01
【问题描述】:

我有一个文本框

 @Html.TextBoxFor(m => m.SingleUnitBarcode, new { @class = "form-control",@id="barcode1", onblur = "CloneData" })

在从这个文本框中失去焦点时,我希望其中的文本显示在另一个文本框中(id =customerbarcode_field)

我正在使用 javascript

<script>
    function CloneData() { 
        var value = document.getElementById("#barcode1").value

        document.getElementById("#customerbarcode_field").value = value;
    }
</script>

但是,当我从第一个文本框失去焦点时,该功能没有被触发。

我错过了什么?

【问题讨论】:

  • 你为什么不用jquery??
  • onblur = "CloneData()" getElementById内的起始#
  • @KyleNeedham,谢谢,# 也是问题的根源。

标签: javascript c# asp.net-mvc asp.net-mvc-4 textbox


【解决方案1】:

您必须将onblur=CloneData 更改为以下:

onblur=CloneData()

此外,您必须更改 DOM 元素的选择。我的意思是您应该更改document.getElementById() 方法中的# 标记。在那里,我们传递了我们想要选择的 DOM 元素的 Id,而不在 Id 之前添加 #。例如,你应该使用这个

document.getElementById("customerbarcode_field")

这个

document.getElementById("#customerbarcode_field")

如果您使用的是JQuery,那么您会选择此元素为:

$('#customerbarcode_field')

【讨论】:

    【解决方案2】:

    像这样修改文本框:

    @Html.TextBoxFor(m => m.SingleUnitBarcode, 
                    new { @class = "form-control",
                          @id="barcode1", 
                          onblur = "CloneData()" })
    

    像这样的脚本,在 javascript 中,您将 javascript 与 jquery 混合:

    <script>
        function CloneData() { 
            var value = document.getElementById("barcode1").value
    
            document.getElementById("customerbarcode_field").value = value;
        }
    </script>
    

    如果你想使用 jquery 那么:

    <script>
            function CloneData() { 
                var value = $("#barcode1").val();
    
                $("#customerbarcode_field").val(value);
            }
        </script>
    

    【讨论】:

      【解决方案3】:

      onblur = "CloneData" 替换为onblur = "CloneData()" 并从id 中删除#

      function CloneData() { 
          var value = document.getElementById("barcode1").value
      
          document.getElementById("customerbarcode_field").value = value;
      }
      

      【讨论】:

        【解决方案4】:

        替换

        @Html.TextBoxFor(m => m.SingleUnitBarcode, new { @class = "form-control",@id="barcode1", onblur = "CloneData" })
        

        用这个:

        @Html.TextBoxFor(m => m.SingleUnitBarcode, new { @class = "form-control",@id="barcode1", onblur = "CloneData();" })
        

        【讨论】:

          【解决方案5】:

          以这种方式将 javascript 事件放入 html 是一种不好的做法。由于您已经在使用 jquery,因此您可以附加一个侦听器而不会污染您的 html;

          $("body").on('blur', '#barcode1', function(){
               $("#customerbarcode_field").val($(this.val());
          });
          

          【讨论】:

            猜你喜欢
            • 2020-04-05
            • 1970-01-01
            • 2020-01-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多