Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda