Is it possible for Javascript to duplicate an element in the DOM?

I have a dropdown menu created from PHP querying the database and then using a foreach to create a list of options for this dropdown menu.

However, in my form, users might need to enter more of the same fields, so I was wondering if it is possible to copy the JavaScript code as a drop-down list with all its values, and then put it in the same form?

Why do I think so, because I cannot find a way to pass the PHP array to JavaScript, or at least I cannot find a way to do this :(

+4
source share
5 answers

I don’t remember the simple javascript method, with jQuery you can use the clone method, however I would not use this because you will get the same message names. It is better to do this in php if you don't need a dynamic form. In this case, the clone is the solution, but keep an eye on the input names.

0
source

Please do not use jQuery for this! jQuery is great, but it makes no sense to include the whole library in something as simple as that. If you are already using jQuery, you should go with the javascript function cloneNode (). Of course, you can also use Ajax to communicate with PHP, but "just" Javascript is faster and easier.

+5
source

Yes, you can do this using the DOM methods, but even better, use jQuery and look at the clone method: http://api.jquery.com/clone/ .

You can pass a PHP array to Javascript by serializing it to a JSON object, but that's a different story.

+2
source

You mean something like

 <select name="top5" size="5" multiple=""> <option>Heino</option> <option>Michael Jackson</option> <option>Tom Waits</option> <option>Nina Hagen</option> <option>Marianne Rosenberg</option> </select> 

This allows you to select several options ( enter link description here )

-1
source

If you want to pass php array to javascript you can do the following:

 var php_array = eval('(' + <?php echo json_encode($php_array); ?> + ')'); 
-1
source

All Articles