reset variable increment javascript

Asked

Viewed 382 times

0

what I need seems to be very simple but I haven’t found a solution yet.

I have that code

var countID = 1;
$("#addArma").click(function (e) {
    e.preventDefault();
    var tipoCampo = "arma";

    adicionaArma(tipoCampo, countID);
    countID++;
});

that normally increments a form within a function I created. What I need is time to delete the form if necessary, I need that when delete it decreases the value and update the variable countID for when I add another form it comes with value in the right sequence.

I did it the way below but when I add another form after it deletes it doesn’t add in the right sequence, I think I have to update the countID variable otherwise, thank you.

$('body').on('click', '#delArma', function (e) {
    e.preventDefault();
    var id = $(this).attr('data-valor');
    var element = $('#armaID' + id);


    element.fadeOut(600);
    countID -= 1;
});

I updated the variable this way and worked, but I add another form after deleting, for example:

form 1 form 2

deleto form 2 add form comes form 2 - here is correct.

if I try to delete form 2 again it does not delete. Function that adds fields:

function adicionaArma(tipo, idContador) {


    var paisFab = "paisFab" + idContador;
    var numArma = "numArma" + idContador;
    var carregamento = "carregamento" + idContador;
    var marca = "marca" + idContador;
    var modelo = "modelo" + idContador;
    var especie = "especie" + idContador;
    var tipoFunc = "tipoFunc" + idContador;
    var calibre = "calibre" + idContador;
    var acabamento = "acabamento" + idContador;
    var qntdCanos = "qntdCanos" + idContador;
    var compCano = "compCano" + idContador;
    var tipoAlma = "tipoAlma" + idContador;
    var numRaias = "numRaias" + idContador;
    var html = "";
    html += '<div id="armaID' + idContador + '"><label class="text-white d-flex justify-content-between">DADOS DA ARMA Nº ' + idContador + '<a href="javascript:void(0);" id="delArma" class="btn btn-danger btn-sm" data-valor="' + idContador + '"><i class="fa fa-trash fa-2x" aria-hidden="true"></i></a></label><hr><div class="form-group"><label for="paisFab">País de Fabricação</label><div class="form-label-group"><select id="' + paisFab + '" class="form-control" ><option value="Brasil" selected="selected">Brasil</option><option value="Afeganistão">Afeganistão</option><option value="África do Sul">África do Sul</option><option value="Albânia">Albânia</option><option value="Alemanha">Alemanha</option><option value="Andorra">Andorra</option>    <option value="Angola">Angola</option>    <option value="Anguilla">Anguilla</option>    <option value="Antilhas Holandesas">Antilhas Holandesas</option>    <option value="Antárctida">Antárctida</option>    <option value="Antígua e Barbuda">Antígua e Barbuda</option>    <option value="Argentina">Argentina</option>    <option value="Argélia">Argélia</option>    <option value="Armênia">Armênia</option>    <option value="Aruba">Aruba</option>    <option value="Arábia Saudita">Arábia Saudita</option>    <option value="Austrália">Austrália</option>    <option value="Áustria">Áustria</option>    <option value="Azerbaijão">Azerbaijão</option>    <option value="Bahamas">Bahamas</option>    <option value="Bahrein">Bahrein</option>    <option value="Bangladesh">Bangladesh</option>    <option value="Barbados">Barbados</option>    <option value="Belize">Belize</option>    <option value="Benim">Benim</option>    <option value="Bermudas">Bermudas</option>    <option value="Bielorrússia">Bielorrússia</option>    <option value="Bolívia">Bolívia</option>    <option value="Botswana">Botswana</option>    <option value="Brunei">Brunei</option>    <option value="Bulgária">Bulgária</option>    <option value="Burkina Faso">Burkina Faso</option>    <option value="Burundi">Burundi</option>    <option value="Butão">Butão</option>    <option value="Bélgica">Bélgica</option>    <option value="Bósnia e Herzegovina">Bósnia e Herzegovina</option>    <option value="Cabo Verde">Cabo Verde</option>    <option value="Camarões">Camarões</option>    <option value="Camboja">Camboja</option>    <option value="Canadá">Canadá</option>    <option value="Catar">Catar</option>    <option value="Cazaquistão">Cazaquistão</option>    <option value="Chade">Chade</option>    <option value="Chile">Chile</option>    <option value="China">China</option>    <option value="Chipre">Chipre</option>    <option value="Colômbia">Colômbia</option>    <option value="Comores">Comores</option>    <option value="Coreia do Norte">Coreia do Norte</option>    <option value="Coreia do Sul">Coreia do Sul</option>    <option value="Costa do Marfim">Costa do Marfim</option>    <option value="Costa Rica">Costa Rica</option>    <option value="Croácia">Croácia</option>    <option value="Cuba">Cuba</option>    <option value="Dinamarca">Dinamarca</option>    <option value="Djibouti">Djibouti</option>    <option value="Dominica">Dominica</option>    <option value="Egito">Egito</option>    <option value="El Salvador">El Salvador</option>    <option value="Emirados Árabes Unidos">Emirados Árabes Unidos</option>    <option value="Equador">Equador</option>    <option value="Eritreia">Eritreia</option>    <option value="Escócia">Escócia</option>    <option value="Eslováquia">Eslováquia</option>    <option value="Eslovênia">Eslovênia</option>    <option value="Espanha">Espanha</option>    <option value="Estados Federados da Micronésia">Estados Federados da Micronésia</option>    <option value="Estados Unidos">Estados Unidos</option>    <option value="Estônia">Estônia</option>    <option value="Etiópia">Etiópia</option>    <option value="Fiji">Fiji</option>    <option value="Filipinas">Filipinas</option>    <option value="Finlândia">Finlândia</option>    <option value="França">França</option>    <option value="Gabão">Gabão</option>   <option value="Gana">Gana</option>    <option value="Geórgia">Geórgia</option>    <option value="Gibraltar">Gibraltar</option>    <option value="Granada">Granada</option>    <option value="Gronelândia">Gronelândia</option>    <option value="Grécia">Grécia</option>    <option value="Guadalupe">Guadalupe</option>    <option value="Guam">Guam</option>    <option value="Guatemala">Guatemala</option>    <option value="Guernesei">Guernesei</option>    <option value="Guiana">Guiana</option>    <option value="Guiana Francesa">Guiana Francesa</option>    <option value="Guiné">Guiné</option>    <option value="Guiné Equatorial">Guiné Equatorial</option>    <option value="Guiné-Bissau">Guiné-Bissau</option>    <option value="Gâmbia">Gâmbia</option>    <option value="Haiti">Haiti</option>    <option value="Honduras">Honduras</option>    <option value="Hong Kong">Hong Kong</option>    <option value="Hungria">Hungria</option>    <option value="Ilha Bouvet">Ilha Bouvet</option>    <option value="Ilha de Man">Ilha de Man</option>    <option value="Ilha do Natal">Ilha do Natal</option>    <option value="Ilha Heard e Ilhas McDonald">Ilha Heard e Ilhas McDonald</option>    <option value="Ilha Norfolk">Ilha Norfolk</option>    <option value="Ilhas Cayman">Ilhas Cayman</option>    <option value="Ilhas Cocos (Keeling)">Ilhas Cocos (Keeling)</option>    <option value="Ilhas Cook">Ilhas Cook</option>    <option value="Ilhas Feroé">Ilhas Feroé</option>    <option value="Ilhas Geórgia do Sul e Sandwich do Sul">Ilhas Geórgia do Sul e Sandwich do Sul</option>    <option value="Ilhas Malvinas">Ilhas Malvinas</option>    <option value="Ilhas Marshall">Ilhas Marshall</option>    <option value="Ilhas Menores Distantes dos Estados Unidos">Ilhas Menores Distantes dos Estados Unidos</option>    <option value="Ilhas Salomão">Ilhas Salomão</option>    <option value="Ilhas Virgens Americanas">Ilhas Virgens Americanas</option>    <option value="Ilhas Virgens Britânicas">Ilhas Virgens Britânicas</option>    <option value="Ilhas Åland">Ilhas Åland</option>    <option value="Indonésia">Indonésia</option>    <option value="Inglaterra">Inglaterra</option>    <option value="Índia">Índia</option>    <option value="Iraque">Iraque</option>    <option value="Irlanda do Norte">Irlanda do Norte</option>    <option value="Irlanda">Irlanda</option>    <option value="Irã">Irã</option>    <option value="Islândia">Islândia</option>    <option value="Israel">Israel</option>    <option value="Itália">Itália</option>    <option value="Iêmen">Iêmen</option>    <option value="Jamaica">Jamaica</option>    <option value="Japão">Japão</option>    <option value="Jersey">Jersey</option>    <option value="Jordânia">Jordânia</option>    <option value="Kiribati">Kiribati</option>    <option value="Kuwait">Kuwait</option>    <option value="Laos">Laos</option>    <option value="Lesoto">Lesoto</option>    <option value="Letônia">Letônia</option>    <option value="Libéria">Libéria</option>    <option value="Liechtenstein">Liechtenstein</option>    <option value="Lituânia">Lituânia</option>    <option value="Luxemburgo">Luxemburgo</option>    <option value="Líbano">Líbano</option>    <option value="Líbia">Líbia</option>    <option value="Macau">Macau</option>   <option value="Macedônia">Macedônia</option>    <option value="Madagáscar">Madagáscar</option>    <option value="Malawi">Malawi</option>    <option value="Maldivas">Maldivas</option>    <option value="Mali">Mali</option>    <option value="Malta">Malta</option>    <option value="Malásia">Malásia</option>    <option value="Marianas Setentrionais">Marianas Setentrionais</option>    <option value="Marrocos">Marrocos</option>    <option value="Martinica">Martinica</option>    <option value="Mauritânia">Mauritânia</option>    <option value="Maurícia">Maurícia</option>    <option value="Mayotte">Mayotte</option>    <option value="Moldávia">Moldávia</option>    <option value="Mongólia">Mongólia</option>    <option value="Montenegro">Montenegro</option>    <option value="Montserrat">Montserrat</option>    <option value="Moçambique">Moçambique</option>    <option value="Myanmar">Myanmar</option>    <option value="México">México</option>    <option value="Mônaco">Mônaco</option>    <option value="Namíbia">Namíbia</option>    <option value="Nauru">Nauru</option>    <option value="Nepal">Nepal</option>    <option value="Nicarágua">Nicarágua</option>    <option value="Nigéria">Nigéria</option>    <option value="Niue">Niue</option>    <option value="Noruega">Noruega</option>    <option value="Nova Caledônia">Nova Caledônia</option>    <option value="Nova Zelândia">Nova Zelândia</option>    <option value="Níger">Níger</option>    <option value="Omã">Omã</option>    <option value="Palau">Palau</option>    <option value="Palestina">Palestina</option>    <option value="Panamá">Panamá</option>    <option value="Papua-Nova Guiné">Papua-Nova Guiné</option>   <option value="Paquistão">Paquistão</option>    <option value="Paraguai">Paraguai</option>    <option value="País de Gales">País de Gales</option>    <option value="Países Baixos">Países Baixos</option>    <option value="Peru">Peru</option>    <option value="Pitcairn">Pitcairn</option>    <option value="Polinésia Francesa">Polinésia Francesa</option>    <option value="Polônia">Polônia</option>    <option value="Porto Rico">Porto Rico</option>    <option value="Portugal">Portugal</option>    <option value="Quirguistão">Quirguistão</option>    <option value="Quênia">Quênia</option>    <option value="Reino Unido">Reino Unido</option>    <option value="República Centro-Africana">República Centro-Africana</option>    <option value="República Checa">República Checa</option>    <option value="República Democrática do Congo">República Democrática do Congo</option>    <option value="República do Congo">República do Congo</option>    <option value="República Dominicana">República Dominicana</option>    <option value="Reunião">Reunião</option>    <option value="Romênia">Romênia</option>    <option value="Ruanda">Ruanda</option>    <option value="Rússia">Rússia</option>    <option value="Saara Ocidental">Saara Ocidental</option>    <option value="Saint Martin">Saint Martin</option>    <option value="Saint-Barthélemy">Saint-Barthélemy</option>    <option value="Saint-Pierre e Miquelon">Saint-Pierre e Miquelon</option>    <option value="Samoa Americana">Samoa Americana</option>    <option value="Samoa">Samoa</option>    <option value="Santa Helena, Ascensão e Tristão da Cunha">Santa Helena, Ascensão e Tristão da Cunha</option>    <option value="Santa Lúcia">Santa Lúcia</option>    <option value="Senegal">Senegal</option>    <option value="Serra Leoa">Serra Leoa</option>    <option value="Seychelles">Seychelles</option>    <option value="Singapura">Singapura</option>    <option value="Somália">Somália</option>    <option value="Sri Lanka">Sri Lanka</option>    <option value="Suazilândia">Suazilândia</option>    <option value="Sudão">Sudão</option>    <option value="Suriname">Suriname</option>    <option value="Suécia">Suécia</option>    <option value="Suíça">Suíça</option>    <option value="Svalbard e Jan Mayen">Svalbard e Jan Mayen</option>    <option value="São Cristóvão e Nevis">São Cristóvão e Nevis</option>    <option value="São Marino">São Marino</option>    <option value="São Tomé e Príncipe">São Tomé e Príncipe</option>    <option value="São Vicente e Granadinas">São Vicente e Granadinas</option>    <option value="Sérvia">Sérvia</option>    <option value="Síria">Síria</option>    <option value="Tadjiquistão">Tadjiquistão</option>    <option value="Tailândia">Tailândia</option>    <option value="Taiwan">Taiwan</option>    <option value="Tanzânia">Tanzânia</option>    <option value="Terras Austrais e Antárticas Francesas">Terras Austrais e Antárticas Francesas</option>    <option value="Território Britânico do Oceano Índico">Território Britânico do Oceano Índico</option>    <option value="Timor-Leste">Timor-Leste</option>    <option value="Togo">Togo</option>    <option value="Tonga">Tonga</option>    <option value="Toquelau">Toquelau</option>    <option value="Trinidad e Tobago">Trinidad e Tobago</option>    <option value="Tunísia">Tunísia</option>    <option value="Turcas e Caicos">Turcas e Caicos</option>    <option value="Turquemenistão">Turquemenistão</option>    <option value="Turquia">Turquia</option>    <option value="Tuvalu">Tuvalu</option>    <option value="Ucrânia">Ucrânia</option>    <option value="Uganda">Uganda</option>    <option value="Uruguai">Uruguai</option>    <option value="Uzbequistão">Uzbequistão</option>    <option value="Vanuatu">Vanuatu</option>    <option value="Vaticano">Vaticano</option>    <option value="Venezuela">Venezuela</option>    <option value="Vietname">Vietname</option>    <option value="Wallis e Futuna">Wallis e Futuna</option>    <option value="Zimbabwe">Zimbabwe</option>    <option value="Zâmbia">Zâmbia</option></select></div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6">            <div class="form-label-group">    <input type="text" id="' + numArma + '" class="form-control" placeholder="Número da Arma" >     <label for="' + numArma + '">Numero da Arma</label></div></div><div class="col-md-6">    <div class="form-label-group">        <input type="text" id="' + carregamento + '" class="form-control" placeholder="Capacidade de Carregamento" >        <label for="' + carregamento + '">Capacidade de Carregamento</label>    </div></div></div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6"> <div class="form-label-group">    <input type="text" id="' + marca + '" class="form-control" placeholder="Marca da Arma" >      <label for="' + marca + '">Marca da Arma</label></div></div><div class="col-md-6">    <div class="form-label-group">       <input type="text" id="' + modelo + '" class="form-control" placeholder="Modelo da Arma" >  <label for="' + modelo + '">modelo da Arma</label></div></div></div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + especie + '" class="form-control" placeholder="Espécie da Arma" >                <label for="' + especie + '">Espécie da Arma</label>            </div>        </div>        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + tipoFunc + '" class="form-control" placeholder="Tipo de Funcionamento" >   <label for="' + tipoFunc + '">Tipo de Funcionamento</label>       </div>       </div>    </div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + calibre + '" class="form-control" placeholder="Calibre da Arma" >                <label for="' + calibre + '">Calibre da Arma</label>            </div>        </div>        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + acabamento + '" class="form-control" placeholder="Acabamento da Arma" >                <label for="' + acabamento + '">Acabamento da Arma</label>            </div>        </div>    </div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + qntdCanos + '" class="form-control" placeholder="Quantidade de Canos" >                <label for="' + qntdCanos + '">Quantidade de Canos</label>            </div>        </div>        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + compCano + '" class="form-control" placeholder="Comprimento do Cano" >                <label for="' + compCano + '">Comprimento do Cano</label>            </div>        </div>    </div></div><div class="form-group">    <div class="form-row">        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + tipoAlma + '" class="form-control" placeholder="Tipo de Alma" >                <label for="' + tipoAlma + '">Tipo de Alma</label>            </div>        </div>        <div class="col-md-6">            <div class="form-label-group">                <input type="text" id="' + numRaias + '" class="form-control" placeholder="Número de Raias/Sentido">                <label for="' + numRaias + '">Numero de Raias</label>            </div>        </div>    </div></div></div>';

    $("#" + tipo).append(html);

}
  • I didn’t get it right, you want a function to delete the last variable and then display the updated value?

  • countID = -1, here you assigned the value -1 to the variable instead of decreasing it. To decrement just do countID-- or countID -= 1.

  • You can place the HTML showing the element you are adding and index this ?

  • I think it’s simpler, I need that when deleting the element, it updates the countID variable that is responsible for incrementing each added form, I do not know if I was clearer.

  • Yes Anderson, I did this way, correcting: so it returns me the sequence I want, but if I try to delete this new form it does not exclude.. example: delete form #2 -> add again it comes with #2, correct, but if I try to delete it does not delete.

2 answers

2


It doesn’t work because when using .fadeOut() the element is not removed from the page, it just wins display: none and stay hidden. With this, when creating a new element, it will have the same id of the element that was hidden, and so, clicking the delete button will fetch the id of the hidden element, because Javascript will fetch the first element that has the id.

Suppose you create two forms. You will have two Divs: #armaID1 and #armaID2, and the variable countID will take the value 3. When removing the div #armaID1, variable will now have the value 2. When creating a new form it will have the same id #armaID2 that already exists, that is, this scheme of decreasing the variable does not work.

The right thing is you don’t decrease the variable countID, so you will always have a form with a new id, although the forms are not sequential, which makes no difference and everything would work perfectly.

But make a correction:

Change the id id="delArma" by class, because you’re repeating it. Delete that id="delArma" and add delArma in the class list of the button, thus:

class="delArma btn btn-danger btn-sm"

1

Guy from what I understand you want the index of your element to auto-increment and auto-create at the click of your add and remove buttons. This here should solve your problem:

$(document).ready(function(){

        var clone = $("seuCampo").html(); // pode ser .clone() tambem //
        $(document).on('click', '#addArma', addArma);

        $(document).on('click', '#delArma', function(){
            $(this).parents("seuCampo").remove();
            increment();
        })

        function addArma() {
            $('body').append(clone);
            increment();
        }


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

Since I didn’t have your HTML, I don’t know what element you’re adding, so instead of this I put the seuCampo in the code, replace with the field that will work. Also note that I incremented by changing your element armaIDof idfor namefor the fact that it’s never good to duplicate things with the same id, you can exchange these all for namewith a []at the end declaring that this will be kind a array, makes it much easier for you to send it to your BD, as it will identify all the values instead of one. Test it and get back to me if you need help or anything like that.

  • thanks for the reply, I updated the post, includes the code of the function to add the fields in html, because I add directly with jquery in div #weapon.

  • Man, seeing the way you do, I think you could make a form a lot more dynamic than it is now. Like I said, you can do an ID counter where you wouldn’t need to have the ID in front of all the other items, you know? When you send it to the BD, you can identify each one by the line ID, you don’t need to have the ID in front of everything. Change the way you build this Form, do it by HTML instead of JS, and only manipulate through Jquery.

  • I understand your point of view, but each form has 14 fields that need to be indexed separately.

  • But this you can do easily. You can put a DIV inside the FORM, where it will encapsulate another or more inside containing all the fields that will be input’s. Taking the function html() of this DIV, you can add all the fields dynamically inside this form, only by manipulating the ID and just filling the fields. When inserting into the BD, you will do a for() through the ID’s and each ID will have the row inserted with its respective fields.

  • got it, I’m not very good at javascript, this function . clone() takes the whole html of an element?

  • In fact no. the clone() literally makes a clone of your element and as soon as you add it it adds as was the previous one. In this case the best would be the html() picking up the parent DIV who told you, by the fact that this function picks up all the code within the DIV that you set, with this you could give a append within this parent DIV, leaving the code more organized.

  • show I’ll try this, then applying your example above I can index with the loop to send to BD right?

  • Yes, this way you can send all items by looping the ID.

Show 3 more comments

Browser other questions tagged

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