0

I'm wondering if JavaScript has a writing format for using html elements that have both single and double quotes inside JavaScript functions. May be something like heredoc for javascript or it could be a function in jQuery. I couldn't find a solution to my problem and will try to describe it below:

I am writing a web page on php. I have a page and there is a form in it. There is a jQuery function that appends select elements to a form. After appending, user selects some options and submit the form. (I really wanted to paste a whole code here to make it clearer, but there is a big amount of code which is not so nice, so I tried to simplify it for you, sorry for some bad code)

I have a php variable like this one (select has onchange event, showUser is a function with AJAX request):

$string = <<<EOT
<select name="sapak[]" onchange='showUser(this.value, document.getElementsByName("dereje[]")[0].value)'>
EOT;

And there are many option in between and of course closing </select>(I didn't write all the code to be shorter). A part of jQuery function that appends select to the form:

$(wrapper).append('<div> <? echo $string; ?> <a href="#" class="remove_field">Del</a></div>');

My problem here is that in $string variable I have to use single and double quotes, and when it comes to append() function in jQuery I use quotes again. And all these give me error in browser's console Uncaught SyntaxError: Unexpected identifier, because of single quotes started at append(' , but ending at onchange=' . Is there are any smart solution for this? I thought that heredoc will be, I've googled and I think that actually there is no heredoc for javascript. May be some other formattings available?

candle
  • 1,963
  • 3
  • 15
  • 24

1 Answers1

1

This should work :

$(wrapper).append("<div> <? echo $string; ?> </div>");

$string = <<<EOT
<select name=\"sapak[]\" onchange=\"showUser(this.value, document.getElementsByName('dereje[]')[0].value)\">
EOT;

As @Imperative advises about character escaping

EdenSource
  • 3,387
  • 16
  • 29