Search code examples
javascriptjqueryclone

Clone form input value as text immediately


Is it possible to clone the value from

<textarea id="text"></textarea>

and

<input id="name" type="input" />

as pure text into a div or paragraph tag immediately?

Example: if "123" is typed in it will clone "123" into the div with no delay.


Solution

  • Yes, use the keydown event and a short 10 ms delay (or possibly less, anything less than 30 is not noticeable by the user).

    $("#text").on("keydown",function(){
        setTimeout(
            // proxy callback to `this` rather than `window`
            $.proxy(function(){ 
                $("#target").text(this.value);
            },this)
        ,10);
    });
    

    Demo: http://jsfiddle.net/7Qrug/

    Edit: If you don't like or understand $.proxy, it could also be written as:

    $("#text").on("keydown",function(){
        var that = this;
        setTimeout(function(){ 
            $("#target").text(that.value);
        },10);
    });