问题描述:

How can I can I alter (change, add, whatever) HTML/text real-time using the input tag? Very similar to the preview interface when asking a question on Stack Overflow minus the code encoding. It just has to be simple.

For example,

<input type="text" name="whatever" />

<div id="example"></div>

Whatever text is entered in the above input tag is added to #example in real-time.

Something involving innerHTML and JavaScript perhaps?

网友答案:

You can do this with jQuery

$('input').keyup(function(){
    var a = $(this).val();
    $('#example').text(a); 
});

Example: http://jsfiddle.net/5TnGT/

网友答案:

There are many other ways to change content than described in the previous answers. Listen for all of them and update realtime. Requires jQuery supporting the newer .on() event handling for this example. Can also use .bind() or .live() with appropriate syntax.

$(document).ready(function() {
    $(document).on('keyup propertychange input paste', 'input', function() {
        $('#example').text($(this).val());
    }); 
});

The second $(document) can be made more specific depending on the markup of the rest of your page.

See also: http://jsfiddle.net/DccuN/2/

网友答案:

Yes javascript will do this. Have a look at on key up. Then either innerHTML as you say or jQuery makes things a bit easier with .append or .html or .text

(Damn too slow)

网友答案:

Plain JavaScript solution (you won't need any sophisticated lib if you don't get too fancy elsewhere):

<input type="text" onkeypress="document.getElementById('example').innerHTML=this.value;" name="whatever" />
<div id="example"></div>
网友答案:

You can bind to the keyup event. Then set the div contents to that of the input.

http://jsfiddle.net/wYqgc/

var input = document.getElementsByTagName('input')[0];
var div = document.getElementById('example');
input.onkeyup = function() {
    div.innerHTML = this.value;
};
网友答案:

You can start with this:

input.onkeyup = function () {
    output.innerHTML = this.value;
};

Live demo: http://jsfiddle.net/P4jS9/

相关阅读:
Top