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

85
Visualizações
Dynamically add new rows to the table

I am creating a table with alpinejs, it should returns new row if someone hit "click to add" link

I have this code:

<div class="mt-2" x-data="services()">
    <tbody class="bg-gray-200" x-model="newService" x-show="services.length">
        <template x-for="service in services" :key="service.id">
            <td x-text="services.length" >     
                <a @click="addService()">Click to add more</a>

<script>                                                    
    function services() {
        return {                                                    
            services: [],
            ,
            newService: '',
            addService() {
                this.services.push({                                        
                    id: this.services.length + 1,                           
                    body: this.newService,                               
                    completed: false                                        
                });                                                         
                this.newService = '';                                       
            },
            deleteService(service){                                     
                let position = this.services.indexOf(service);              
                this.services.splice(position, 1);                          
            }                                                           
        }                                                           
    }                                                           
</script>                                                   

but instead of returning a new row it returns 23 rows at ones!!

how can I fix that?

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

0

Adding to the existing answer, here is a simple working example.

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
<script src="//unpkg.com/alpinejs" defer></script>

<div class="mt-4 flex flex-col max-w-lg mx-auto" x-data="services()">
  <div class="flex space-x-2">
    <input type="text" x-model="newService" class="px-2 py-1 border flex-1 rounded" placeholder="Service">
    <button class="border bg-blue-600 hover:bg-blue-700 text-white rounded px-4 py-1" @click="addService()">Add
      service</button>
  </div>
  <div x-show="services.length">
    <div class="rounded border mt-4 text-xs">
      <table class="w-full">
        <thead>
          <tr>
            <th class="bg-gray-100 font-normal text-gray-500 uppercase py-2">Services</th>
          </tr>
        </thead>
        <tbody>
          <template x-for="service in services" :key="service.id">
            <tr class="border-t">
              <td class="flex justify-between items-center px-4 py-1">
                <span x-text="service.body"></span>
                <button class="text-sm uppercase text-red-500 px-2 py-1 rounded hover:bg-red-100"
                  @click="deleteService(service.id)">x</button>
              </td>
          </template>
        </tbody>
      </table>

    </div>
    <button class="text-xs w-full mt-2 bg-red-100 text-red-400 px-2 py-2 rounded hover:bg-red-200" @click="services = []">Delete
      All</button>
  </div>
</div>



<script>
  function services() {
    return {
      services: [{
          id: 1,
          body: 'Service 1',
          completed: false
        },
        {
          id: 2,
          body: 'Service 2',
          completed: false
        }
      ],
      newService: '',
      addService() {
        if (this.newService.length < 1) return;
        this.services.push({
          id: Date.now(),
          body: this.newService,
          completed: false
        });
        this.newService = '';
      },
      deleteService(serviceId) {
        let position = this.services.findIndex(el => el.id == serviceId);
        this.services.splice(position, 1);
      }
    }
  }
</script>

about 4 years ago · Juan Pablo Isaza Relatório

0

With limited code and without a working example it is bit hard to give a concrete answer. By looking at the code, I think you are getting the existing number of rows in your table body.

addService() {
    this.services.push({                                        
        id: this.services.length + 1,                           
        body: this.newService,                               
        completed: false                                        
    });                                                         
    this.newService = '';                                       
}

In this method you are selecting this.newService as your body. And looking at your HTML <tbody class="bg-gray-200" x-model="newService" x-show="services.length"> newService is the entire body of the existing table.

So you are getting the existing 23 rows.

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