Search code examples
jqueryappendhtml-escape-characters

Appending javascript to div with jquery


I'm trying to append the following javascript to a div that will appear when the user presses the ESC key. I can't seem to get the JavaScript to display the value of the javascript being used:

    $("#json").hide();
    $(document).keydown(function (e) {
    if (e.keyCode == 27) {
         $("#json").append("<script type="text/javascript"> + "window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value;" + "</" + script>").toggle();
    }
});

I'm not sure where I'm missing string escaping or a quotation mark.


Solution

  • I think the problem is with the quotes:

    $('#json').append('<' + script type="text/javascript">window.location.href = "/editorialPortal?' + this.id + '=' + this.options[this.selectedIndex].value + '"  </' + 'script>').toggle();
    

    In this example, I use single quotes in defining strings, so the double quotes can be used inside it.

    Also, be sure to include jQuery in your fiddles. The above code works except that it errors on the undefined variables this.options[this.selectedIndex].value and this.id. Breaking up of the script tags is to make jsfiddle happy.