How to combine my jQuery

I have 10 fields that will be displayed in live view before sending

Example

$(function () {
    $(".word").keyup(function () {
        var word = $(this).val();
        $(".word_preview").html(word);
        return false;
    });
    $("#title").keyup(function () {
        var title = $(this).val();
        $(".title_preview").html(title);
        return false;
    });

   .......... more .............

    $("#desc").keyup(function () {
        var desc = $(this).val();
        $(".desc_preview").html(desc);
        return false;
    });
});

Now I have to write this code 10 times. Is there a way to combine this?

+3
source share
1 answer

You can do something like the following:

$(".word, #desc, #title...").keyup(function () {
  var word = $(this).val();
  $("."+$(this).attr('id')+"_preview").html(word);
  return false;
});

Change . As suggested by Andrew, there is no need to use a jQuery wrapper:

$(".word, #desc, #title...").keyup(function () {
  var word = this.value;
  $("."+this.id+"_preview").html(word);
  return false;
});

Thank you Andrey!

+4
source

Source: https://habr.com/ru/post/1784421/


All Articles