Get the value Jquery of button with same id = 'remove'

2

Good day friends I have a problem, I have a foreach where I printed a botton with id="remove" with different value, I would like to press the button to send the value of that button and then process it with an ajax request and send that data per post.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<br>
<button id="remover" value="PC150">ELIMINAR</button> 
<br>
<button id="remover" value="GSX20">ELIMINAR</button> 
<br>
<button id="remover" value="TC300">ELIMINAR</button> 
<br>
<button id="remover" value="QW300">ELIMINAR</button> 
<br>
  
</div>

More or less like that are my buttons but with different value. How can I get the value of the button I am pressing even if they all have the same ID = 'remove' ?, and then send that value per post to another page.

    
asked by Manueel Perezz 30.03.2018 в 22:19
source

2 answers

3

There is a concept that you are forgetting, the identifiers (ID) must be unique always.

Just as your code HTML is incorrect, instead of ID you could use classes and add the appropriate listener for the event click .

//Seleccionamos los elementos con la clase remover
var botones = document.querySelectorAll('.remover');
//Iteramos los elemetos obtenidos
botones.forEach(el =>{
  // Añadimos el Listener par el evento click
  el.addEventListener('click',(e)=>{
    //Imprimimos en consola en value del botón clickeado
    // el botón estará referenciado por e.target
    console.log(e.target.value);
  })
})
<button class="remover" value="PC150">ELIMINAR</button> 
<br>
<button class="remover" value="GSX20">ELIMINAR</button> 
<br>
<button class="remover" value="TC300">ELIMINAR</button> 
<br>
<button class="remover" value="QW300">ELIMINAR</button>

With Jquery It would be easier

$('.remover').click(function(e) {
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="remover" value="PC150">ELIMINAR</button> 
<br>
<button class="remover" value="GSX20">ELIMINAR</button> 
<br>
<button class="remover" value="TC300">ELIMINAR</button> 
<br>
<button class="remover" value="QW300">ELIMINAR</button>
    
answered by 30.03.2018 / 22:31
source
1

I think you have to change things a bit, first by the HTML standard you can not have identical ids, so when you print them you will have to concatenate in the ID some identified, be it a sequential integer or up to the same value.

After this, what you need to do in javascript is to bind those buttons to the onclick event to send the data via ajax.

    
answered by 30.03.2018 в 22:54