最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alter HTML real-time with input tag - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jan 28, 2012 at 3:21 UserIsCorruptUserIsCorrupt 5,04515 gold badges40 silver badges42 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 2

You can do this with jQuery

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

Example: http://jsfiddle/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/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/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/P4jS9/

发布评论

评论列表(0)

  1. 暂无评论