Help with function to add and remove Divs with Autoincrement

Asked

Viewed 71 times

1

I made a code to add a DIV (wrap-products) with all the HTML elements that are inside it as soon as the "+" button is pressed. Each DIV is added one below the other with the same characteristics, what changes is the autoincrement that is done in the "Number" and its Names and id’s. Each DIV gets on its right an "X" button, where this button needs to delete the DIV to which it belongs, that is, each button deletes its index. How can I do this function, where when deleting the DIV of choice, it is done automatically the decrease of the index of the "Number", for example, if you have the Number 1,2,3,4 and I delete the 3, the Number 4 goes to 3, and the next add will be the 4 again.

index php.:

<div id="allProducts" name="allProducts">
    <div class="produtos-wrap" id="wrap-produtos-1" name="wrap-produtos-1"> <!---- div que é clonada !---->
        <div class=" text-center select_height">
            <b>Número:</b>
            <div id="index" class="font-pop">1</div>
        </div>

        <div class=" select_height" id="div_produtos">
            <b>Produto:</b>
            <select class="selectpicker form-control" data-show-subtext="false" data-live-search="true" name="select_produtos-1" id="select_produtos-1" onchange="initProdutos(1);">
                <?php
                foreach ($result2 as $item_produtos) {
                    echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
                    . $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
                }
                ?>
            </select>
        </div>

        <div class="text-center select_height">
            <b>Embalagem:</b>
            <br>
            <input type="text" maxlength="2" class="edit-input font-pop" id="embalagem-1" name="embalagem-1" value="">
        </div>

        <div class="text-center select_height">
            <b>Preço:</b>
            <br>
            <input type="text" maxlength="5" id="preco-1" name="preco-1" class="edit-input font-pop">
        </div>

        <div class="text-center select_height">
            <b>Quantidade:</b>
            <br>
            <input type="text" maxlength="3" class="edit-input font-pop" value="0" id="quantidade-produto-1" name="quantidade-produto-1">
        </div>

        <div class="text-center select_height">
            <b>Preço do Produto:</b>
            <div id="preco-produto-1" name="preco-produto-1" class="font-pop"></div>
        </div>

        <div class="text-center select_height">
            <button id="remove-1" name="remove-1" class="remover-1" onclick="remove()">X</button>
        </div>
    </div>  
    <hr>
</div>
<button id="add-button" onclick="addProduct()">+</button>

Elements.php ( where do I bring the content to add the Divs ):

<?php $id = $_GET['id']; ?>
<div class="produtos-wrap" id="wrap-produtos-<?= $id ?>" name="wrap-produtos-<?= $id ?>">
    <div class=" text-center select_height">
        <b>Número:</b>
        <div id="index" class="font-pop"><?= $id ?></div>
    </div>

    <div class=" select_height" id="div_produtos">
        <b>Produto:</b>
        <select class="selectpicker form-control" data-show-subtext="false" data-live-search="true" name="select_produtos-<?= $id ?>" id="select_produtos-<?= $id ?>" onchange="initProdutos(<?= $id ?>);">
            <?php
            foreach ($result2 as $item_produtos) {
                echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
                . $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
            }
            ?>
        </select>
    </div>

    <div class="text-center select_height">
        <b>Embalagem:</b>
        <br>
        <input type="text" maxlength="2" class="edit-input font-pop" id="embalagem-<?= $id ?>" name="embalagem-<?= $id ?>" value="">
    </div>

    <div class="text-center select_height">
        <b>Preço:</b>
        <br>
        <input type="text" maxlength="5" id="preco-<?= $id ?>" name="preco-<?= $id ?>" class="edit-input font-pop">
    </div>

    <div class="text-center select_height">
        <b>Quantidade:</b>
        <br>
        <input type="text" maxlength="3" class="edit-input font-pop" value="0" id="quantidade-produto-<?= $id ?>" name="quantidade-produto-<?= $id ?>">
    </div>

    <div class="text-center select_height">
        <b>Preço do Produto:</b>
        <div id="preco-produto-<?= $id ?>" name="preco-produto-<?= $id ?>" class="font-pop"></div>
    </div>

    <div class="text-center select_height">
        <button id="remove-<?= $id ?>" name="remove-<?= $id ?>" class="remover-<?= $id ?>">X</button>
    </div>
</div>  
<hr>

Function addProduct():

var index = 1;

function addProduct() {
    var id = index + 1;
    $.ajax({
        type: "GET",
        url: "elements.php?id=" + id,
        //CASO DÊ TUDO CERTO
        success: function(data) {
            var div = document.getElementById('allProducts');
            div.innerHTML += data;
            index = id;
        },
        error: function(request, error) {
            console.log(error);
            // console.log("Request: " + JSON.stringify(request));
        }
    });
}

Function remove():

function remove() {
    const remover = $('.remover');
    const div = $('#produtos-wrap-');
    remover.onclick(div.remove());
    index - 1;
}

1 answer

1

I don’t know if I got it right, but I did this very basic example.

It has two models, one removes the brother from above and himself, and the other is a son who removes the father and himself. So if your button comes after the element you use the prev(), but if the button is inside a parent you use the parent()

$('.brow').on('click', function () {
	$(this).prev('div').remove();
	$(this).remove();
});
$('.pai').on('click', function () {
	$(this).parent('div').remove();
	$(this).remove();
});
.pai,
.brow {
	border: 1px solid #000;
	cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<div id="test">
	<div class="">p irmão 1</div>
	<div class="brow">remove irmão de cima 1</div>

	<div class="">p irmão 2</div>
	<div class="brow">remove irmão de cima 2</div>

	<div class="">Div pai 1
		<div class="pai">Filho remove pai 1</div>
	</div>

	<div class="">Div pai 2
		<div class="pai">Filho remove pai 2</div>
	</div>
	
</div>

NOTE: There may be a way to optimize this code, but I did it the way I found it simpler to understand.

  • Hugo, good afternoon. That’s not exactly what I need. With each add I give, another div is created and its elements receive a self-aincrement in their index, for example "wrap-products-1", "wrap-products-2", "wrap-products-3" and so on. I managed to do a function, I put a class "remove" on the "X" buttons of each DIV, even the ones that are added. My problem is now being the following, when I delete the last DIV, there is no decreasing of the index of the " Number ", that is, if I delete the number 4, the next add comes with the number 5, and not the 4 again. Can you help me?

  • I will edit the question with the code and the current problem.

  • @Leonardohenriquefaleiros yes now it was very clear! But unfortunately for this case I will not have technical knowledge to solve :/ . You would have to check if there are already any items, if yes starts counting by the last index + 1, or if there is no one starting from 0. But unfortunately I do not have this knowledge. But you rephrasing the question, someone in the community can help you. Another problem will be to "recalculate" the index of all if you remove the first, or other element in the middle of the listing...

Browser other questions tagged

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