I have a page with a form where the user can add multiple items to the form by using a [+]
button. The plus button is adding another set of fields to enter more data every time it is clicked.
Right now the javascript code is just appending some HTML string with jQuery, but I'd like to do this in a cleaner way just like Magento 2 is doing this with their x-magento-template blocks, like:
<script id="some-template" type="text/x-magento-template">
<div class="wrapper">
<input id="<%- data.id %>" name="<%- data.name %>" placeholder="<%- data.placeholder %>" />
</div>
</script>
How can I now take this template and render it with the input of a data
object? And after that, append it to my form?
The JS I have (of which I'm going to put the HTML in newField
into the x-magento-template):
define([
"jquery",
"mage/translate",
"domReady!"
], function($) {
$("button#js-add-more").click(function(e) {
e.preventDefault();
var newField = '<div class="wrapper"><input id="field-' + ($('form#myform input[id^=field-]').length + 1) + ' " name="field[]" placeholder="' + $.mage.__('Enter data') + '" /></div>';
$('form#myform').append(newField);
});
});