Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
Get the closest & highest id using javascript

i have two lists one for products to select and the other for the selected products i want to be able to return the selected product to its original place.

I kinda solve it in the following format but the issue is it might be hundreds of products

$(document).on('click', "#remove_product", function () {
    var product = $(this).parents("li"),
        found = false;
    $('.products_list li').each(function() {
        if(this.id > product.attr('id') && !found ){
            product.clone().insertBefore(this); 
            found = true;
        }
    });
    if(!found) product.clone().append(".products_list");
    product.remove();
})
.products_list button{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="products_list">
  <li id="1">Content 1</li>
  <li id="2">Content 2</li>
  <li id="4">Content 4</li>
  <li id="5">Content 5</li>
</ul>

<hr>

<ul class="selected_products">

  <li id="3">
    Content 3
    <button id="remove_product">remove product</button>
  </li>

</ul>

Any better solution?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The simplest way to achieve your goal would be to create a function which sorts the li elements within the ul based on their id. You can then call this function whenever an update is made to the li.

The function can also be made generic enough to work for both ul containers, when adding/removing an item from each.

Note in the example below that I added the button element to each li by default, as per your pattern of hiding them through CSS for the initial list. I also changed the id on the button to a class, as id need to be unique.

With that said, try this:

let $productsList = $('.products_list');
let $selectedList = $('.selected_products');
let sortProductsInContainer = $container => $container.find('li').sort((a, b) => a.id > b.id ? 1 : -1).appendTo($container);

// add product to selected list
$productsList.on('click', 'li', e => {
  $(e.target).closest('li').appendTo($selectedList);
  sortProductsInContainer($selectedList);
});

// remove product from selected list
$selectedList.on('click', ".remove_product", e => {
  $(e.target).closest("li").appendTo($productsList);
  sortProductsInContainer($productsList);
})
.products_list button {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="products_list">
  <li id="1">Content 1 <button class="remove_product">remove product</button></li>
  <li id="2">Content 2 <button class="remove_product">remove product</button></li>
  <li id="4">Content 4 <button class="remove_product">remove product</button></li>
  <li id="5">Content 5 <button class="remove_product">remove product</button></li>
</ul>

<hr>

<ul class="selected_products">
  <li id="3">Content 3 <button class="remove_product">remove product</button></li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda