Search code examples
dynamicinputdhtmlpreview

DHTML - Change text on page using input field


I need to create a code to change an example text to a user-defined value when the user types in an input field (Similar to the preview field when writing a question on Stack Overflow).

This needs to be achieved without the use of HTML5 or Flash as the users will be running IE8, not all will have Flash plug-ins installed.

As such I have started by looking at DHTML to achieve the desired effect. Currently I can change the example text when a user types in the input field but only to a pre-defined value ("Example" in the code below), how should I edit this code to display the user-defined value?

JS

    function changetext(id)
{
id.innerHTML="Example";
}

HTML

<form>
Content:<input type="text" id="input" onkeyup="changetext(preview)" />  
</form>

<p id="preview">No content found</p> 

Solution

  • You need to have something like this in the function:

    function changetext(id){
       var info = document.getElementById('input').value();
       id.innerHTML = info;
    }
    

    This js is not fully correct. I would highly recommend you start using a javascript library like jQuery. It makes this a menial task.

    Edited:

    jQuery will work in IE8 just fine. in jQuery you will not need to attach js to your input. The code would look like this.

    $('#input').click(function(){
        $('#preview).html(this.val());
    });
    

    It is a lot cleaner and doesnt have js in the html.