简体   繁体   中英

Text from one textbox to another using JavaScript

I have a textbox as

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

And on losing focus from this textbox I want the text in it to be displayed in another textbox(with id =customerbarcode_field)

I am using the javascript

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

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

However the function is not being triggered when I lose focus from the first textbox.

What did i miss ?

You have to change the onblur=CloneData , to the the following one:

onblur=CloneData()

Also, you have to change the selecting of the DOM elements. I mean you should change the # tag in the document.getElementById() method. There we pass the Id of the DOM element we want to select without prepending the # before the Id . For instance, you should use this

document.getElementById("customerbarcode_field")

insted of this

document.getElementById("#customerbarcode_field")

If you were using JQuery , then you would have selected this element as:

$('#customerbarcode_field')

Modify the TextBox like this:

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

and script like this, in javascript you are mixing javascript with jquery:

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

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

if you want to do with jquery then:

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

            $("#customerbarcode_field").val(value);
        }
    </script>

replace onblur = "CloneData" by onblur = "CloneData()" and remove # from id

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

    document.getElementById("customerbarcode_field").value = value;
}

Replace

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

with this:

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

It's bad practice to put your javascript event in the html in that manner. Since you are using jquery already you can attach a listener without polluting your html;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM