3

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);
    });

});
  • 1
    I think the best way to do this would be with Knockout templates, similar to how the checkout is built. This live example may help. – Ben Crook May 8 '17 at 10:48
5

I found out how to do this. You can use mage/template to use these x-magento-template JS templates and render them.

define([
    "jquery",
    "mage/template",
    "mage/translate",
    "domReady!"
], function($, mageTemplate) {

    $("button#js-add-more").click(function(e) {
        e.preventDefault();

        var num = $('form#myform input[id^=field-]').length + 1,
            template = mageTemplate('#some-template');

        var newField = template({
            data: {
                id: 'field-' + num,
                name: 'field[]',
                placeholder: $.mage.__('Enter data')
            }
        });

        $('form#myform').append(newField);
    });

});

And the some-template is like I also posted in my question:

<script id="some-template" type="text/x-magento-template">
    <div class="wrapper">
        <input id="<%- data.id %>" name="<%- data.name %>" placeholder="<%- data.placeholder %>" />
    </div>
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.