php – Need help with jQuery to clone form dropdown (dynamic dropdown) – Education Career Blog

I am using PHP to generate dynamic dropdown, the dropdown list items are fetched from database.

Here’s the php code for that and it works.

<select name="title" id="title">
<?php $categories = Category::find_by_cid(5); foreach($categories as $category): ?>
<option value="<?php echo $category->name; ?>"><?php echo $category->name; ?></option>
<?php endforeach; ?>

What i want to do is, Using jQuery whenever a link with id AddNew is clicked, a new dropdown should appear below that, containing same values.

Also, is there any way to execute php code inside javascript??

ex :

var name = "<?php echo $user->name; ?>";


To clone elements, you can use jQuery’s .clone() method (obviously):

$('#addNew').click(function() {

Note that ID’s should be unique on the page, if you are going to clone the select element, give it a class instead of ID.

And yes, you can “use” PHP in JavaScript, provided that the file is processed with PHP. Just note that you are not actually accessing PHP with JavaScript, but rather creating JavaScript files dynamically.


Use jQuery .clone() method.


Also, is there any way to execute php code inside javascript??

Not really, no. PHP is executed server-side, so in the example you provided:

var name = "<?php echo $user->name; ?>";

That will turn out to be:

var name = "Josh";

at run-time, when the javascript has access to it. The php code is executed, then rendered to html where the javascript finally sees it. What you are doing is dynamically creating javascript rather than executing php code.

Leave a Comment