Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy text of a field into another automatically

I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.

If the user deletes the text in field_1, it should also get automatically deleted in field_2.

I've tried this but it doesn't work:

<script type="text/javascript">
$(document).ready(function () {

function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>

Any ideas?

like image 626
adrian.m123 Avatar asked Dec 05 '22 23:12

adrian.m123


1 Answers

You are almost there... The function is correct, you just have to assign it to the change event of the input:

<script type="text/javascript">
    $(document).ready(function () {

        function onchange() {
            //Since you have JQuery, why aren't you using it?
            var box1 = $('#field_1');
            var box2 = $('#field_2');
            box2.val(box1.val());
        }
        $('#field_1').on('change', onchange);
    });

like image 101
LcSalazar Avatar answered Dec 18 '22 13:12

LcSalazar