How to create a code snippet dynamically in Javascript?

Asked

Viewed 49 times

0

Hello, I am making a form for college project and would like to know how to create a code block dynamically by pressing a button.

I have the code snippet below that is part of my form:

<div class="wrap-input bg-white">
    <input class="input" name="empresa" type="text" placeholder="Qual foi a empresa?" />
</div>
<div class="wrap-input bg-white rs2-wrap-input">
    <input class="input" name="cargo" type="text" placeholder="Qual foi seu cargo?" />
</div>
<div class="wrap-input bg-white rs2-wrap-input">
    <label class="label-input">Entrada</label>
    <input class="input" type="month" name="empresa_entrada" placeholder="Mês">
</div>
<div class="wrap-input bg-white rs2-wrap-input">
    <label class="label-input">Saída</label>
    <input class="input" type="month" name="empresa_saida">
</div>
<div class="wrap-input bg-white">
    <textarea class="input" name="principais_atividades" rows="3"
              placeholder="Descreva as principais atividades desempenhadas no cargo..."></textarea>
</div>
<button class="button">Adicionar outra experiência</button>

By clicking the button I would like to "duplicate" this block of inputs for the person to add a new experience.

How to do this, what do I want to do in Javascript?

2 answers

2

I suggest you add a div around each group of inputs, so you can easily select a group. Then you can activate a function when the button is pressed and in that function you create a clone/copy with the same content (hence the true in the .cloneNode(true). Before entering this group you need to delete the copied values.

An example would be like this:

function adicionarExperiencia() {
  const formulario = document.querySelector('.formulario-experiencia');
  if (!formulario) return;
  const novoFormulario = formulario.cloneNode(true);
  const campos = novoFormulario.querySelectorAll('input, textarea');
  for (let campo of campos) {
    campo.value = '';
  }
  formulario.parentElement.appendChild(novoFormulario);
}
<div class="formulario-experiencia">
  <div class="wrap-input bg-white">
    <input class="input" name="empresa" type="text" placeholder="Qual foi a empresa?" />
  </div>
  <div class="wrap-input bg-white rs2-wrap-input">
    <input class="input" name="cargo" type="text" placeholder="Qual foi seu cargo?" />
  </div>
  <div class="wrap-input bg-white rs2-wrap-input">
    <label class="label-input">Entrada</label>
    <input class="input" type="month" name="empresa_entrada" placeholder="Mês">
  </div>
  <div class="wrap-input bg-white rs2-wrap-input">
    <label class="label-input">Saída</label>
    <input class="input" type="month" name="empresa_saida">
  </div>
  <div class="wrap-input bg-white">
    <textarea class="input" name="principais_atividades" rows="3" placeholder="Descreva as principais atividades desempenhadas no cargo..."></textarea>
  </div>
</div>
<button class="button" onclick="adicionarExperiencia()">Adicionar outra experiência</button>

  • Okay, I’ll try to do that. Thanks for the tip.

0

Good morning. I made a code using Jquery so that you can have control of the number of "Forms" created, where there is an index with autoincrement and dynamic decrement ( because I also added a delete button). Take the test:

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .formulario-experiencia {
            margin-bottom: 1em;
            line-height: 2;
        }

        .input_edit {
            border: none;
            outline: none;
        }

        .index_div {
            margin-bottom: .5em;
        }
    </style>
    <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>
    <script src="script.js"></script>
</head>
<body>

<div id="wrap-form">
    <div class="formulario-experiencia">
        <div class="index_div">
            <b>Formulário n°: </b>
            <input name="index_form[]" value="1" class="input_edit" readonly="true">
        </div>

        <div class="wrap-input bg-white">
            <input class="input" name="empresa" type="text" placeholder="Qual foi a empresa?"/>
        </div>
        <div class="wrap-input bg-white rs2-wrap-input">
            <input class="input" name="cargo" type="text" placeholder="Qual foi seu cargo?"/>
        </div>
        <div class="wrap-input bg-white rs2-wrap-input">
            <label class="label-input">Entrada</label>
            <input class="input" type="month" name="empresa_entrada" placeholder="Mês">
        </div>
        <div class="wrap-input bg-white rs2-wrap-input">
            <label class="label-input">Saída</label>
            <input class="input" type="month" name="empresa_saida">
        </div>
        <div class="wrap-input bg-white">
        <textarea class="input" name="principais_atividades" rows="3"
                  placeholder="Descreva as principais atividades desempenhadas no cargo..."></textarea>
        </div>
        <div>
            <button class="excluir_form">X</button>
        </div>
    </div>

</div>

<br>
<div>
    <button class="button" id="add-button">Adicionar outra experiência</button>
</div>
</body>
</html>
$(document).ready(function () {
    var clone = $('#wrap-form').html();
    $(document).on('click', '#add-button', addProd);

    function addProd() {
        $('#wrap-form').append(clone);
        ids();
    }

    $(document).on('click', '.excluir_form', function () {
        $(this).parents('.formulario-experiencia').remove();
        ids();
    });

    function ids() {
        $("[name='index_form[]']").each(function (i, e) {
            $(e).val(i + 1);
        });
    }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.