<p>I'll be flat-out honest; I didn't read through your code. Secondly, I think to set expectations when you say a matrix field on the front-end you'll need to understand it isn't going to look like what you think it looks like within the CP.</p>

<p>With that said, on a site I am working on, I have a page where a user can update their profile on the front-end. There is a section they can add multiple contact info - which links to a matrix filed in the CP.</p>

<p><strong>twig</strong></p>

<pre><code>&lt;input type="hidden" name="fields[contactInfo]"&gt;

&lt;h3&gt;&lt;label for="contactInfo"&gt;Contact Info&lt;/label&gt;&lt;/h3&gt;
{% for block in currentUser.contactInfo.type('contact') %}
    &lt;div class="matrixblock"&gt;
        &lt;input type="hidden" name="fields[contactInfo][{{ block.id }}][type]" value="contact"&gt;
        &lt;input type="hidden" name="fields[contactInfo][{{ block.id }}][enabled]" value="1"&gt;

        &lt;input type="text" name="fields[contactInfo][{{ block.id }}][fields][firstName]" value="{{ block.firstName }}"&gt;
        &lt;input type="text" name="fields[contactInfo][{{ block.id }}][fields][lastName]" value="{{ block.lastName }}"&gt;
        &lt;input type="tel" name="fields[contactInfo][{{ block.id }}][fields][phoneNumber]" value="{{ block.phoneNumber }}"&gt;
        &lt;input type="email" name="fields[contactInfo][{{ block.id }}][fields][email]" value="{{ block.email }}"&gt;
        &lt;span&gt;&lt;a href="javascript:void(0);" class="remove-contact"&gt;&lt;i class="fa fa-times"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;
    &lt;/div&gt;
{% endfor %}
&lt;button type="button" id="addPerson"&gt;Add Person&lt;/button&gt;
</code></pre>

<p>The above is what defines what I'll call a row in your matrix field. It will pull in and render any existing matrix blocks that have been created. You'll need to update the <code>type</code> to whatever you have called it in your project.</p>

<p>To add a new "row" I used <a href="https://craftcms.stackexchange.com/questions/6551/how-to-update-matrix-field-on-frontend-for-user-profile">this thread</a> and <a href="https://craftcms.stackexchange.com/questions/1318/how-to-get-matrix-editor-into-frontend">this thread</a> to get me in the right direction. I highly recommend reading them. I think I read them both 20+ times.</p>

<p>Where I know my code falls short is in the javascript. I am currently hard-coding the html. Ideally I'd like to have it clone the existing markup so I don't have to update it multiple places in the event it changes.</p>

<p><strong>jquery</strong></p>

<pre><code>/**
 * Event listener to add additional primary guardian(s).
 *
 * @param {object} event | The click event.
 *
 */
var blocknum = 1;

$('#addPerson').click(function (event) {
    var markup = '&lt;div class="matrixblock"&gt;&lt;input type="hidden" name="fields[contactInfo][new' + blocknum + '][type]" value="contact"&gt;&lt;input type="hidden" name="fields[contactInfo][new' + blocknum + '][enabled]" value="1"&gt;&lt;input type="text" name="fields[contactInfo][new' + blocknum + '][fields][firstName]" value=""&gt;&lt;input type="text" name="fields[contactInfo][new' + blocknum + '][fields][lastName]" value=""&gt;&lt;input type="tel" name="fields[contactInfo][new' + blocknum + '][fields][phoneNumber]" value=""&gt;&lt;input type="email" name="fields[contactInfo][new' + blocknum + '][fields][email]" value=""&gt;&lt;span&gt;&lt;a href="javascript:void(0);" class="remove-contact"&gt;&lt;i class="fa fa-times"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;';
    $('div.matrixblock:last').after(markup);
    blocknum++;
});
</code></pre>

<p>As you will notice, you will also need a way to delete the given row. This is my example, you will need to update the logic to match your current html structure.</p>

<p><strong>jquery</strong></p>

<pre><code>/**
 * Event listener to removing additional primary guardian(s).
 *
 * @param {object} event | The click event.
 *
 */
$('body').on('click', '.remove-contact', function (event) {
    $(this).parent().parent().fadeOut('fast').remove();
    event.preventDefault();
});
</code></pre>

<p><strong>Note:</strong> Because we are dynamically creating rows, we need to register/bind the click event in this manor so that all <em>future</em> clicks will be attached to this event.</p>

<p>I have not styled my form at all, but in the end, this is what the above markup renders:</p>

<p><a href="https://i.sstatic.net/SqsgB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SqsgB.png" alt="enter image description here"></a></p>

<p>(first name, last name, email, phone)</p>

<p>Hope this helps!</p>

CC BY-SA 4.0
2020-07-17T20:36:36.440Z
I was surprised there were not more posts addressing this question. Thank you so much for posting the solution. I was able to adapt it for my own uses. I am not savvy enough to clone the first div, but I still got it to work.
4midori
CC BY-SA 3.0
2015-12-01T14:57:10.553Z
2017-01-25T23:21:10.407Z
2017-04-13T12:50:59.930Z
Damon
<p>What is the best course of action to allow the creation/deletion of matrix fields in front-end. For context this in a Commerce Order Field. JS is mess right now, any underlying Craft JS libraries I can tap into?</p>

<p>Here is the whole mess below, having issues with users getting stuck here if they accidentally leave of the matrix fields empty.</p>

<pre><code>{#
 # 2016 Apply-3
 # ---------------
 #}

{% extends '_layouts/_event-checkout' %}

{% block content_inside %}
&lt;section&gt;
    &lt;div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1"&gt;
        &lt;div class="feature boxed bg-secondary"&gt;
        &lt;form method="post"&gt;
      &lt;input type="hidden" name="action" value="commerce/cart/updateCart"&gt;
      &lt;input type="hidden" name="redirect" value="apply/review"/&gt;
            &lt;input type="hidden" name="paymentMethodId" value="2"&gt;
            &lt;input type="hidden" name="fields[applicationProgress]" value="2"&gt;
            &lt;input type="hidden" name="fields[applicationSchemaVersion]" value="{{ switchboard.applicationSchemaVersion }}"&gt;

      &lt;div class="text-center"&gt;
            &lt;h4 class="uppercase mt48 mt-xs-0"&gt;Great, Now we know you {{ application.shippingAddress.firstName }}!&lt;/h4&gt;
            &lt;p class="lead mb64 mb-xs-24"&gt;
                Now let's see what you know!
            &lt;/p&gt;
      &lt;/div&gt;

      {{ getCsrfInput() }}

            &lt;hr class="mt16"&gt;
            &lt;div class="row mt64"&gt;
                &lt;div class="col-sm-12 input-with-label"&gt;
                    &lt;span&gt;Tell me something that's true, that almost nobody agrees with you on.&lt;/span&gt;
                    &lt;textarea name="fields[thielQuestion]"
                        placeholder="Some may recognize this famous question, we want some original answers though, really think about this one."&gt;{{ application.thielQuestion }}&lt;/textarea&gt;
                &lt;/div&gt;
                &lt;div class="col-sm-12 mt48 input-with-label"&gt;
                    &lt;span&gt;What are YOU passionate about?&lt;/span&gt;
                    &lt;textarea name="fields[whatAreYouPassionateAbout]"
                        placeholder="What are YOU passionate about?"&gt;{{ application.whatAreYouPassionateAbout }}&lt;/textarea&gt;
                &lt;/div&gt;
                &lt;div class="col-sm-12 mt48 input-with-label"&gt;
                    &lt;span&gt;What songs are included on the soundtrack to your life?&lt;/span&gt;
                    &lt;textarea name="fields[lifeSoundtrack]"
                        placeholder="One of the most important question on this application."&gt;{{ application.lifeSoundtrack }}&lt;/textarea&gt;
                &lt;/div&gt;
            &lt;/div&gt;

            &lt;hr class="mt16"&gt;
      &lt;div class="row mt16"&gt;
        &lt;div class="skills col-sm-12 col-md-7 col-lg-9"&gt;
          &lt;div class="skills__list twelve columns"&gt;
            &lt;h3 class="skills__list-title"&gt;Add some skills by clicking the options on the right!&lt;/h3&gt;
                        {% for bloc in application.skills %}
            &lt;div class="skills input-with-label text-left"&gt;
              {% if bloc.type == "programmingLanguage" %}
                &lt;p&gt;+ Programming Language&lt;/p&gt;
                                &lt;input type="hidden" name="fields[skills][new{{ loop.index }}][type]" value="{{ bloc.type }}"&gt;
                                &lt;span&gt;Language Name:&lt;/span&gt;
                &lt;input type="text" name="fields[skills][new{{ loop.index }}][fields][languageName]" value="{{ bloc.languageName }}" placeholder="Language Name"&gt;
                                &lt;span&gt;Years Of Proficiency:&lt;/span&gt;
                &lt;input type="text" name="fields[skills][new{{ loop.index }}][fields][yearsOfProficiency]" value="{{ bloc.yearsOfProficiency }}" placeholder="Years Of Proficiency"&gt;
              {% elseif bloc.type == "programmingFramework"%}
                &lt;p&gt;+ Programming Framework&lt;/p&gt;
                                &lt;input type='hidden' name='fields[skills][new{{ loop.index }}][type]' value="{{ bloc.type }}"&gt;
                &lt;span&gt;Framework Name:&lt;/span&gt;
                &lt;input type="text" name="fields[skills][new{{ loop.index }}][fields][frameworkName]" value="{{ bloc.frameworkName }}" placeholder="Framework Name"&gt;
                &lt;span&gt;Coolest Thing You Have Built:&lt;/span&gt;
                &lt;textarea name="fields[skills][new{{ loop.index }}][fields][coolestThing]" placeholder="What is the coolest thing you have built with it?"&gt;{{ bloc.coolestThing }}&lt;/textarea&gt;
                            {% elseif bloc.type == "knowledge"%}
                &lt;p&gt;+ Knowledge&lt;/p&gt;
                                &lt;input type='hidden' name='fields[skills][new{{ loop.index }}][type]' value="{{ bloc.type }}"&gt;
                                &lt;span&gt;Programmers alone can&amp;apos;t solve these great challenges we need people like you with that special know-how, maybe it&amp;apos;s in environmental sciences, maybe it&amp;apos;s in Politics? Whatever you know something extra about:&lt;/span&gt;
                &lt;textarea name="fields[skills][new{{ loop.index }}][fields][knowledge]" placeholder="Programmers alone can&amp;apos;t solve these great challenges we need people like you with that special know-how, maybe it&amp;apos;s in environmental sciences, maybe it&amp;apos;s in Politics? Whatever you know something extra about!"&gt;{{ bloc.knowledge }}&lt;/textarea&gt;
                            {% elseif bloc.type == "expirience"%}
                &lt;p&gt;+ Expirience&lt;/p&gt;
                                &lt;input type='hidden' name='fields[skills][new{{ loop.index }}][type]' value="{{ bloc.type }}"&gt;
                                &lt;span&gt;Worked at one of those cool tech companies, or maybe been involved in hackathons in past?&lt;/span&gt;
                &lt;textarea name="fields[skills][new{{ loop.index }}][fields][expirience]" placeholder="Worked at one of those cool tech companies, or maybe been involved in hackathons in past?"&gt;{{ bloc.knowledge }}&lt;/textarea&gt;

                            {% endif %}
            &lt;/div&gt;
                        &lt;hr&gt;
            {% endfor %}
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="col-sm-12 col-md-5 col-lg-3"&gt;

          &lt;div class="skills-buttons"&gt;
            &lt;a href="#" class="btn btn-sm skills__button" data-type="programmingLanguage"&gt;+ Programming Language&lt;/a&gt;
            &lt;a href="#" class="btn btn-sm skills__button" data-type="programmingFramework"&gt;+ Programming Framework&lt;/a&gt;
            &lt;a href="#" class="btn btn-sm skills__button" data-type="knowledge"&gt;+ Knowledge&lt;/a&gt;
            &lt;a href="#" class="btn btn-sm skills__button" data-type="experience"&gt;+ Experience&lt;/a&gt;
            &lt;!-- &lt;a href="#" class="btn skills__button" data-type="proveYourAwesomness"&gt;+ Prove Your Awesomness&lt;/a&gt;
            &lt;a href="#" class="btn skills__button" data-type="showYourThinkingProwess"&gt;+ Show Your Thinking Prowess&lt;/a&gt; --&gt;
          &lt;/div&gt;

        &lt;/div&gt;
      &lt;/div&gt;

      &lt;input type="submit" class="button button-primary" value="Continue"&gt;
        &lt;/form&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/section&gt;
{% includejs %}
var $skills = $('.skills__button');

{% if cart.skills %}
    var $iter = {{ cart.skills|length }};
{% else %}
    var $iter = 0;
{% endif %}

$skills.on('click', function() {
  var $type = $(this).attr("data-type");
  var $humanType = $(this).text();
  $iter++;

  console.log('Adding Block');
  if($type == "programmingLanguage") {
    $('.skills__list').append("\
    &lt;div class='skills'&gt; \
      &lt;p&gt;"+$humanType+"&lt;/p&gt; \
      &lt;input type='hidden' name='fields[skills][new"+$iter+"][type]' value='"+$type+"'&gt; \
      &lt;input type='text' name='fields[skills][new"+$iter+"][fields][languageName]' placeholder='Language Name'&gt; \
      &lt;input type='text' name='fields[skills][new"+$iter+"][fields][yearsOfProficiency]' placeholder='Years Of Proficiency'&gt; \
    &lt;/div&gt;");
  }else if($type == "programmingFramework") {
    $('.skills__list').append("\
    &lt;div class='skills'&gt; \
      &lt;p&gt;"+$humanType+"&lt;/p&gt; \
      &lt;input type='hidden' name='fields[skills][new"+$iter+"][type]' value='"+$type+"'&gt; \
      &lt;input type='text' name='fields[skills][new"+$iter+"][fields][frameworkName]' placeholder='Framework Name'&gt; \
      &lt;textarea name='fields[skills][new"+$iter+"][fields][coolestThing]' placeholder='What is the coolest thing you have built with it?'&gt;&lt;/textarea&gt; \
    &lt;/div&gt;");
  }else if($type == "knowledge") {
    $('.skills__list').append("\
    &lt;div class='skills'&gt; \
      &lt;p&gt;"+$humanType+"&lt;/p&gt; \
      &lt;input type='hidden' name='fields[skills][new"+$iter+"][type]' value='"+$type+"'&gt; \
      &lt;textarea name='fields[skills][new"+$iter+"][fields][knowledge]' placeholder='Programmers alone can&amp;apos;t solve these great challenges we need people like you with that special know-how, maybe it&amp;apos;s in environmental sciences, maybe it&amp;apos;s in Politics? Whatever you know something extra about!'&gt;&lt;/textarea&gt; \
    &lt;/div&gt;");
  }else if($type == "expirience") {
    $('.skills__list').append("\
    &lt;div class='skills'&gt; \
      &lt;p&gt;"+$humanType+"&lt;/p&gt; \
      &lt;input type='hidden' name='fields[skills][new"+$iter+"][type]' value='"+$type+"'&gt; \
      &lt;textarea name='fields[skills][new"+$iter+"][fields][expirience]' placeholder='Worked at one of those cool tech companies, or maybe been involved in hackathons in past?'&gt;&lt;/textarea&gt; \
    &lt;/div&gt;");
  }
});

{% endincludejs %}
{% endblock %}
</code></pre>

<matrix><frontend>
Managing Frontend JS for Matrix Fields
# Managing Frontend JS for Matrix Fields

(Asked by: username_0 on 2015-12-01)

What is the best course of action to allow the creation/deletion of matrix fields in front-end. For context this in a Commerce Order Field. JS is mess right now, any underlying Craft JS libraries I can tap into?
Here is the whole mess below, having issues with users getting stuck here if they accidentally leave of the matrix fields empty.
{#
 # 2016 Apply-3
 # ---------------
 #}

{% extends '_layouts/_event-checkout' %}

{% block content_inside %}

    
        
        
      
      
            
            
            

      
            Great, Now we know you {{ application.shippingAddress.firstName }}!
            
                Now let's see what you know!
            
      

      {{ getCsrfInput() }}

            
            
                
                    Tell me something that's true, that almost nobody agrees with you on.
                    {{ application.thielQuestion }}
                
                
                    What are YOU passionate about?
                    {{ application.whatAreYouPassionateAbout }}
                
                
                    What songs are included on the soundtrack to your life?
                    {{ application.lifeSoundtrack }}
                
            

            
      
        
          
            Add some skills by clicking the options on the right!
                        {% for bloc in application.skills %}
            
              {% if bloc.type == "programmingLanguage" %}
                + Programming Language
                                
                                Language Name:
                
                                Years Of Proficiency:
                
              {% elseif bloc.type == "programmingFramework"%}
                + Programming Framework
                                
                Framework Name:
                
                Coolest Thing You Have Built:
                {{ bloc.coolestThing }}
                            {% elseif bloc.type == "knowledge"%}
                + Knowledge
                                
                                Programmers alone can't solve these great challenges we need people like you with that special know-how, maybe it's in environmental sciences, maybe it's in Politics? Whatever you know something extra about:
                {{ bloc.knowledge }}
                            {% elseif bloc.type == "expirience"%}
                + Expirience
                                
                                Worked at one of those cool tech companies, or maybe been involved in hackathons in past?
                {{ bloc.knowledge }}

                            {% endif %}
            
                        
            {% endfor %}
          
        
        

          
            + Programming Language
            + Programming Framework
            + Knowledge
            + Experience
            
          

        
      

      
        
        
    

{% includejs %}
var $skills = $('.skills__button');

{% if cart.skills %}
    var $iter = {{ cart.skills|length }};
{% else %}
    var $iter = 0;
{% endif %}

$skills.on('click', function() {
  var $type = $(this).attr("data-type");
  var $humanType = $(this).text();
  $iter++;

  console.log('Adding Block');
  if($type == "programmingLanguage") {
    $('.skills__list').append("\
     \
      "+$humanType+" \
       \
       \
       \
    ");
  }else if($type == "programmingFramework") {
    $('.skills__list').append("\
     \
      "+$humanType+" \
       \
       \
       \
    ");
  }else if($type == "knowledge") {
    $('.skills__list').append("\
     \
      "+$humanType+" \
       \
       \
    ");
  }else if($type == "expirience") {
    $('.skills__list').append("\
     \
      "+$humanType+" \
       \
       \
    ");
  }
});

{% endincludejs %}
{% endblock %}

**Tags:** matrix, frontend

---

## 1 answers

### Answer by username_1 on 2015-12-01. Score: 6

I'll be flat-out honest; I didn't read through your code. Secondly, I think to set expectations when you say a matrix field on the front-end you'll need to understand it isn't going to look like what you think it looks like within the CP.
With that said, on a site I am working on, I have a page where a user can update their profile on the front-end. There is a section they can add multiple contact info - which links to a matrix filed in the CP.
twig


Contact Info
{% for block in currentUser.contactInfo.type('contact') %}
    
        
        

        
        
        
        
        
    
{% endfor %}
Add Person

The above is what defines what I'll call a row in your matrix field. It will pull in and render any existing matrix blocks that have been created. You'll need to update the type to whatever you have called it in your project.
To add a new "row" I used this thread and this thread to get me in the right direction. I highly recommend reading them. I think I read them both 20+ times.
Where I know my code falls short is in the javascript. I am currently hard-coding the html. Ideally I'd like to have it clone the existing markup so I don't have to update it multiple places in the event it changes.
jquery
/**
 * Event listener to add additional primary guardian(s).
 *
 * @param {object} event | The click event.
 *
 */
var blocknum = 1;

$('#addPerson').click(function (event) {
    var markup = '';
    $('div.matrixblock:last').after(markup);
    blocknum++;
});

As you will notice, you will also need a way to delete the given row. This is my example, you will need to update the logic to match your current html structure.
jquery
/**
 * Event listener to removing additional primary guardian(s).
 *
 * @param {object} event | The click event.
 *
 */
$('body').on('click', '.remove-contact', function (event) {
    $(this).parent().parent().fadeOut('fast').remove();
    event.preventDefault();
});

Note: Because we are dynamically creating rows, we need to register/bind the click event in this manor so that all future clicks will be attached to this event.
I have not styled my form at all, but in the end, this is what the above markup renders:

(first name, last name, email, phone)
Hope this helps!

> **Comments:**
> **username_2**: I was surprised there were not more posts addressing this question. Thank you so much for posting the solution. I was able to adapt it for my own uses. I am not savvy enough to clone the first div, but I still got it to work.  

---

