Copy text of a field into another automatically

后端 未结 8 1202
攒了一身酷
攒了一身酷 2020-12-16 08:32

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

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 08:43

    If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.

    Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.

    var $field1 = $("#field_1");
    var $field2 = $("#field_2");
    
    $field1.on("keydown",function(){
       setTimeout(checkValue,0); 
    });
    
    var v2 = $field2.val();
    var checkValue = function(){
        var v1 = $field1.val();
        if (v1 != v2){
            $field2.val(v1);
            v2 = v1;
        }
    };
    
    

提交回复
热议问题