Close Form Dynamically jQuery

Asked

Viewed 168 times

1

The form is a registration form for a cat hotel. The form has the option to add more than one cat per registration, so I clone the cat’s registration form to include the second cat, but I can’t get the clone form to be closed by a Close button. I know that, because it is dynamic, it is not possible to use . remove(), but I tried other ways and I haven’t yet. Follow the code the last way I tried:

$(document).ready(function() {

  var elm_html = $('#clone-form').html();
  var remover = document.getElementById('remove');
  var i = $('.cadastroGato').length;
  setMask();

  $(document).on('click', '.clonador', function(e) {
    e.preventDefault();
    remover.style.display = "inline-block";

    var elementos = elm_html.replace(/\[[0\]]\]/g, '[' + i++ + ']');
    $('#clone-form').append(elementos);
    setMask();
  });

  $('.remover').on('click', function(e) {
    e.preventDefault();
    $(this).parent('#cloonedForm[' + (i - 1) + ']').remove();
  })

  if (i == 0) {
    remover.style.display = "none";
  }

  function setMask() {
    $('.rg').mask('00.000.000-0');
    $('.cpf').mask('000.000.000-00');
    $('.cep').mask('00000-000');
    $('.res').mask('(00) 0000-0000');
    $('.cel').mask('(00) 00000-0000');
    $('.date').mask('00/00/0000');
  }

});
label {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>

<div id="clone-form">
    <div id="cloonedForm[0]" class="cadastroGato" style="margin-top: 70px;">
        <h3>Dados do gato</h3>
        <hr style="margin-bottom: 70px;" class="hr-color2" />
        <label>
            <input type="text" name="nome-gato[0]" placeholder="Nome*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="apelido[0]" placeholder="Apelidos*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" class="date" name="nascimento[0]" placeholder="Data de nascimento*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="raca[0]" placeholder="Raça*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="cor[0]" placeholder="Cor*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <select name="sexo[0]">
            <option class="selectClass" value="masc">Sexo*:</option>
            <option class="selectClass" value="masc">Masculino</option>
            <option class="selectClass" value="fem">Feminino</option>
        </select>

        <label>
            <input type="text" class="date" name="vacina[0]" placeholder="Última vacinação*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" class="date" name="antirrabica[0]" placeholder="Antirrábica*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <p>
            <label>Vacinas em dia?
                <br>
                <input type="radio" name="vacinas[0]" value="sim" required>Sim
                <input type="radio" name="vacinas[0]" value="nao">Nao
            </label>
        </p>

        <label onclick="alergiaQual()">Tem alguma doença ou alergia?
            <input type="radio" name="alergia[0]" value="sim" required>Sim
            <input type="radio" name="alergia[0]" value="nao">Nao
        </label>

        <label id="qualAlergia" style="visibility: hidden;">
            <input type="text" name="qual[0]" placeholder="Qual?" value="" />
        </label>

        <label class="register">Castrado?
            <br />
            <input type="radio" name="castrado[0]" value="sim" required>Sim
            <input type="radio" name="castrado[0]" value="nao">Nao
        </label>

        <label onclick="medicacao()">Toma alguma medicação?
            <br>
            <input type="radio" name="medicacao[0]" value="sim" required>Sim
            <input type="radio" name="medicacao[0]" value="nao">Nao
        </label>

        <label id="qualMedicacao" style="visibility: hidden;">
            <input type="text" name="med[0]" placeholder="Qual?" value="" />
        </label>
        <br>
        <label onclick="alimentacao()">
            Necessita alimentação especial?
            <br>
            <input type="radio" name="alimentacao[0]" value="sim" required>Sim
            <input type="radio" name="alimentacao[0]" value="nao">Nao
        </label>

        <label id="qualAlimentacao" style="visibility: hidden;">
            <input type="text" name="alimentacaoo[0]" placeholder="Qual?" value="" />
        </label>
        <br>
        <label onclick="fiv()">
            Já realizou teste para FIV e FELV?
            <br>
            <input type="radio" name="teste[0]" value="sim" required>Sim
            <input type="radio" name="teste[0]" value="nao">Nao
        </label>

        <label id="testeFiv" class="register" style="display: none;">
            <input type="radio" name="fiv[0]" value="posfiv">Positivo para FIV
            <input type="radio" name="fiv[0]" value="posfelv">Positivo para FELV
            <input type="radio" name="fiv[0]" value="posambos">Positivo para ambos
            <input type="radio" name="fiv[0]" value="negambos">Negativo para ambos
        </label>

        <label class="register">
            Já ficou em hotelzinho antes?
            <p>
                <input type="radio" name="hotelzinho[0]" value="sim" required>Sim
                <input type="radio" name="hotelzinho[0]" value="nao">Nao</p>
        </label>

        <label class="message">
            <textarea name="temperamento[0]" placeholder="Descreva o temperamento do seu gato (exemplo: tímido, assustado, carinhoso, agressivo, etc)*:" data-constraints='@Required @Length(min=20,max=999999)' data-constraints="@Required"></textarea>
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <label class="message">
            <textarea name="descricao[0]" placeholder="Descreva a rotina do seu gato (o que gosta, não gosta, hábitos, etc)*:" data-constraints='@Required @Length(min=20,max=999999)' data-constraints="@Required"></textarea>
            <span class="empty-message">*Campo obrigatório</span>
        </label>
    </div>
    <div id="status" style="visibility: hidden;"></div>
</div>

<button type="button" class="clonador">Adicionar Gato</button>
<button type="button" id="remove" class="remover" style="display: none;">Remover Gato</button>
<button type="submit" id="enviar" name="submit">Enviar</button>

That’s the code where I clone the form. I did a read, and I even tried other ways, but the close button always has no action and no error in the log. Follow the registration form of the cat, is without the tag form, but it is because I will not put the whole form here for being well extended

  • Where’s the "close" button? It’s the button with the id "remove"?

  • That, is the button with id "remove", I left with the None display so that the button appears only when you have at least one clone

1 answer

1


I wouldn’t use [ ] in an id, use cloonedForm1, ids may have some incompatibilities in the way of writing. Depending on the browser and the DOM version. In this case the incompatibility is pq jQuery uses the brackets to filter several things in selector, for example input[name=nome]. Ids started by numbers, for example, is also not recommended. To write ids, choose to use only letters, numbers only at the end. Forget any other character or spaces.

Another mistake you made was using the variable i in .remover. click Count because it is only counted at the beginning of the script execution, so I changed to:

$('#cloonedForm' + ( $('.cadastroGato').length - 1) ).remove();

And also replace the id of the default object that will be cloned: var elementos = elm_html.replace('cloonedForm0', 'cloonedForm' + $('.cadastroGato').length );

It would look like this so:

$(document).ready(function() {

  var elm_html = $('#clone-form').html();
  var remover = document.getElementById('remove');

  setMask();

  $(document).on('click', '.clonador', function(e) {
    e.preventDefault();
    remover.style.display = "inline-block";

    var elementos = elm_html.replace('cloonedForm0', 'cloonedForm' + $('.cadastroGato').length );
    $('#clone-form').append(elementos);
    setMask();
  });

  $('.remover').on('click', function(e) {
    e.preventDefault();
    $('#cloonedForm' + ( $('.cadastroGato').length - 1) ).remove();
  })

  if (i == 0) {
    remover.style.display = "none";
  }

  function setMask() {
    $('.rg').mask('00.000.000-0');
    $('.cpf').mask('000.000.000-00');
    $('.cep').mask('00000-000');
    $('.res').mask('(00) 0000-0000');
    $('.cel').mask('(00) 00000-0000');
    $('.date').mask('00/00/0000');
  }

});

And the html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>

<div id="clone-form">
    <div id="cloonedForm0" class="cadastroGato" style="margin-top: 70px;">
        <h3>Dados do gato</h3>
        <hr style="margin-bottom: 70px;" class="hr-color2" />
        <label>
            <input type="text" name="nome-gato[0]" placeholder="Nome*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="apelido[0]" placeholder="Apelidos*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" class="date" name="nascimento[0]" placeholder="Data de nascimento*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="raca[0]" placeholder="Raça*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" name="cor[0]" placeholder="Cor*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <select name="sexo[0]">
            <option class="selectClass" value="masc">Sexo*:</option>
            <option class="selectClass" value="masc">Masculino</option>
            <option class="selectClass" value="fem">Feminino</option>
        </select>

        <label>
            <input type="text" class="date" name="vacina[0]" placeholder="Última vacinação*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>
        <label>
            <input type="text" class="date" name="antirrabica[0]" placeholder="Antirrábica*:" value="" data-constraints="@Required" />
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <p>
            <label>Vacinas em dia?
                <br>
                <input type="radio" name="vacinas[0]" value="sim" required>Sim
                <input type="radio" name="vacinas[0]" value="nao">Nao
            </label>
        </p>

        <label onclick="alergiaQual()">Tem alguma doença ou alergia?
            <input type="radio" name="alergia[0]" value="sim" required>Sim
            <input type="radio" name="alergia[0]" value="nao">Nao
        </label>

        <label id="qualAlergia" style="visibility: hidden;">
            <input type="text" name="qual[0]" placeholder="Qual?" value="" />
        </label>

        <label class="register">Castrado?
            <br />
            <input type="radio" name="castrado[0]" value="sim" required>Sim
            <input type="radio" name="castrado[0]" value="nao">Nao
        </label>

        <label onclick="medicacao()">Toma alguma medicação?
            <br>
            <input type="radio" name="medicacao[0]" value="sim" required>Sim
            <input type="radio" name="medicacao[0]" value="nao">Nao
        </label>

        <label id="qualMedicacao" style="visibility: hidden;">
            <input type="text" name="med[0]" placeholder="Qual?" value="" />
        </label>
        <br>
        <label onclick="alimentacao()">
            Necessita alimentação especial?
            <br>
            <input type="radio" name="alimentacao[0]" value="sim" required>Sim
            <input type="radio" name="alimentacao[0]" value="nao">Nao
        </label>

        <label id="qualAlimentacao" style="visibility: hidden;">
            <input type="text" name="alimentacaoo[0]" placeholder="Qual?" value="" />
        </label>
        <br>
        <label onclick="fiv()">
            Já realizou teste para FIV e FELV?
            <br>
            <input type="radio" name="teste[0]" value="sim" required>Sim
            <input type="radio" name="teste[0]" value="nao">Nao
        </label>

        <label id="testeFiv" class="register" style="display: none;">
            <input type="radio" name="fiv[0]" value="posfiv">Positivo para FIV
            <input type="radio" name="fiv[0]" value="posfelv">Positivo para FELV
            <input type="radio" name="fiv[0]" value="posambos">Positivo para ambos
            <input type="radio" name="fiv[0]" value="negambos">Negativo para ambos
        </label>

        <label class="register">
            Já ficou em hotelzinho antes?
            <p>
                <input type="radio" name="hotelzinho[0]" value="sim" required>Sim
                <input type="radio" name="hotelzinho[0]" value="nao">Nao</p>
        </label>

        <label class="message">
            <textarea name="temperamento[0]" placeholder="Descreva o temperamento do seu gato (exemplo: tímido, assustado, carinhoso, agressivo, etc)*:" data-constraints='@Required @Length(min=20,max=999999)' data-constraints="@Required"></textarea>
            <span class="empty-message">*Campo obrigatório</span>
        </label>

        <label class="message">
            <textarea name="descricao[0]" placeholder="Descreva a rotina do seu gato (o que gosta, não gosta, hábitos, etc)*:" data-constraints='@Required @Length(min=20,max=999999)' data-constraints="@Required"></textarea>
            <span class="empty-message">*Campo obrigatório</span>
        </label>
    </div>
    <div id="status" style="visibility: hidden;"></div>
</div>

<button type="button" class="clonador">Adicionar Gato</button>
<button type="button" id="remove" class="remover" style="display: none;">Remover Gato</button>
<button type="submit" id="enviar" name="submit">Enviar</button>
  • I didn’t know they might have problems using [] in ids, thanks for the tip. It worked, it is removing the clones, but now it is not increasing in the inputs Names, I can put this increment in the same replace()?

  • I didn’t notice this detail, sorry.... but I believe that if you put only [] in the name of the field it will understand which number is according to the order in the document. I have not tested this, but usually it works in php and other languages, I see pq not not work in html tb.

  • for example name="nome-gato[]" When you have two fields with this, it should post atutomatically with Dice 0 and 1

  • or replace [0] var elementos = elm_html.replace('cloonedForm0', 'cloonedForm' + $('.cadastroGato').length ).replace(/\[[0\]]\]/g, '[' + $('.cadastroGato').length + ']');

  • The html hadn’t worked, I was trying something like var elementos = elm_html.replace('cloonedForm0', 'cloonedForm' + $('.cadastroGato').length ) + (/\[[0\]]\]/g, '[' + i++ + ']');, but my logic was a little wrong. Your way worked perfectly. Honestly, I don’t know how long it would take me to catch this mistake, so thank you!

Browser other questions tagged

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