将图像传递给textarea

I'm trying to make smileys work, so I'm going to post the full problem, maybe someone knows a better solution. I have this chat system, where you can click on a smiley and it's value gets passed to the <textarea> much like Google hangouts. Value is "smile_n" where 20 > n > 0. I store it like that in the database, and I have PHP code that's in charge of displaying the proper <img src="smile_n"> tag when parsing data from SQL, but when I pick a smiley, it will write "smile_n" in the <textarea>. Is there ways to change this?

Here's how I drop smileys into the <textarea> element:

$(".smilepick").click(function(){
 $('#chatty').val($('#chatty').val()+(' ')+$(this).attr('href')+(' '));
  var el = $("#chatty").get(0);
  var elemLen = el.value.length;
  el.selectionStart = elemLen;
  el.selectionEnd = elemLen;
  el.focus();
});

Can I somehow make it parse "smile_n" words into images, but keep the value that gets inserted into database "smile_n" so PHP code won't fail?

If you could use div with contenteditable, you could start with something like this:

HTML

<div id="editable" contenteditable="true">
Everything contained within this div is editable in browsers that support.
</div>

Jquery

var smile_ha_img = '<img src="http://placehold.it/16x16"/>';

$('#editable').keyup(function() {
    $(this).html(function(i, v) {
        return v.replace('smile-ha', smile_ha_img);   
    });
});

It will replace every smile-ha with the given image.

Try it here: http://jsfiddle.net/tb8vQ/1/ Type smile-ha into paragraph on 4th panel.

Then you can make the content of the div be copied to a hidden textarea to be send by your form as usual.

To Do

  • You must optmize it for the amount of smiles to check and replace.
  • After the function replace the string with the html, the carret position is placed on beginning of string (at least in my browser). There are a lot of answers here in Stackoverflow about how to solve this.
  • The keyup trigger used here would not be useful for your system if users doesn't type the smile code themselves. But you can change your function to be executed right after the user chose the emoticon.

Another approach There are some WYSIWYG editors that allow you to choose which features you want to offer to your users. So maybe you could find one that you could hide all options but emoticons.