使用JavaScript将文本从一个文本框发送到另一个

Text from one textbox to another using JavaScript

本文关键字:文本 一个 另一个 JavaScript 使用      更新时间:2023-09-26

我有一个文本框作为

 @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>

然而,当我从第一个文本框中失去焦点时,该功能不会被触发。

我错过了什么?

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

onblur=CloneData()

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

document.getElementById("customerbarcode_field")

代替这个

document.getElementById("#customerbarcode_field")

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

$('#customerbarcode_field')

这样修改TextBox:

@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>

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

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

更换

@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();" })

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

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