PHP: How to correctly echo classes and id's for jQuery to render

2170 views javascript
10

This might seem like noob question but I'm trying to echo this:

echo 'jQuery(document.body).prepend("<div id="notice" class="alert 
alert-success">Advanced Custom Fields plugin is currently active. 
</div>");';

so this can get rendered using jQuery. If I do this, the editor won't show any hightlight error, but the code won't render. I just get this in the console:

Uncaught SyntaxError: missing ) after argument list

Problem is related to the id="notice" and the class="alert alert-success" and the way jQuery renders it.

If I try this:

echo 'jQuery(document.body).prepend("<div id='notice' class='alert 
alert-success'>Advanced Custom Fields plugin is currently active. 
</div>");';

(notice the single quotes). I get highlight errors in the code and the following error:

Parse error: syntax error, unexpected 'notice' (T_STRING), expecting ',' or ';'

Any ideas on how to correctly echo this id and class?

Thanks a lot!

answered question

1 Answer

1

You need to escape your quotes inside your string with backslashes:

echo 'jQuery(document.body).prepend("<div id=\'notice\' class=\'alert alert-success\'>Advanced Custom Fields plugin is currently active.</div>");';

posted this

Have an answer?

JD

Please login first before posting an answer.