auto show preview from text box

2020-03-31 05:02发布

问题:

I'm making a post page for my website, and I would like to add an auto update preview box, showing what is being typed into the text box above. Obviously i'd like to use javascript, or jquery. And the thing I need is basically the same thing as on the ask page for this website!

回答1:

Are you looking for .keyup()?

Look at this fiddle for a simple example: http://jsfiddle.net/LUDWQ/2/

$('#tb1').keyup(function() {
    $('#tb2').val($('#tb1').val());
});

When putting in into a div and not another textbox you can use this:

$('#tb1').keyup(function() {
    $('#tb2').html($('#tb1').val()); //tb2 is a <div> here
});

Fiddle: http://jsfiddle.net/LUDWQ/4/



回答2:

If the textarea control has an id of "textarea_control" and the preview div/span/whatever has an id of "preview", you could potentially use something like this (snagged from some code I used in a project and tweaked for your example).

//Wait for input in textarea
$("#textarea_control").keyup(function() {
  var inputB = $(this).val();
  if(globalTimeout != null){
    clearTimeout(globalTimeout);
  }
  //Give the user a slight time to delay while typing
  globalTimeout = setTimeout(function(){
    $("#preview").html(inputB);
  }, 1000); 

Hope this helps!

Please note, this does not do any filtering of user's input, so you should probably think about calling a separate function to filter the data to prevent injection or other attacks before displaying the preview.



标签: jquery forms