Pass the variable to the javascript function with symbols like colon, semicolon, and so on.


Currently I am stock on this scenario on my current function.

Basically, this ajax call will generate list of emoticons, however I want that when a user clicks on a smiley image, the smiley code will be added to message textbox.

Like for example, when user clicks on smiling image, the :-) code will be added to the message box. My question is, Is it possible to pass the code :-) to a function?

On my current codes, addText(' + key + ') is not working. The value of key is :-). Error says Uncaught SyntaxError: Unexpected token : And when the value is ;) the error is Uncaught SyntaxError: Unexpected token ; I also have :lol: etc. codes similar to that. Any help will be much appreciated.

    type: "POST",
    async: true,
    cache: false,
    dataType: "json",
    url: "./assets/php/scripts.php",
    data: {command: 'get-smileys'},
    success: function (data) {
        var div_obj = document.createElement("ul");
        $.each(data, function(key, value) {
            $(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" onclick="addText(' + key + ');"><br>' + key + '</div></li>')

And here's the function in adding text part:

function addText(text){
    var fullMessage = $("#message").val();
    $("#message").val(fullMessage + text);

The problem is you need to pass them as string literals as given below.

'" onclick="addText(\'' + key + '\');"><br>'

But a better solution will be to use a jQuery event handler instead of a inline one like

$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img class="smileys" src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" data-smiley="' + key + '"><br>' + key + '</div></li>')


jQuery(function ($) {
    $("#smileys").on('click', '.smileys', function () {