How can I send the id along with an event in js

3

My question is if I can send the id of a tag in html along with the same event that executes it, for example:

<button id="boton" onclick="mandarId()">

and when the event happens send the id of the tag too.

    
asked by F. Juarez 04.11.2016 в 11:59
source

3 answers

8

Another option, considered a best practice, is to use unobtrusive javascript (Unobtrusive JavaScript ) which implies, among other things, separating the presentation of functionality.

It is about linking the event from javascript and not from HTML, with the advantage (among others) that you always receive the event, instead of having to be passing parameters. As the event has the information of who received the same, this can be used to, for example, reuse handlers (callbacks).

In the following example, we assume that you have several buttons and depending on the ID you want to do one thing or another. You could do the following:

// esta es la funcion que invocan todos los botones
function manejadorCallback(evento) {

  // cada vez que clickas un boton. Automaticamente se invoca con un parametro
  // que es el Evento. el cual tiene una propiedad (entre otras) llamada target
  // que es el elemento que dispara el evento. Luego buscas el id en target.
  alert(evento.target.id);  
}

// aqui el javascript no obstructivo.

// obtenemos todos los botones, por su clase
var buttons = document.querySelectorAll('.miboton')

// a cada uno le asignamos el manejador del evento.
for(var i = 0; i < buttons.length; i++) {

   // aqui generas el equivalente a onclick
   buttons[i].addEventListener('click', manejadorCallback);
}
<button id="elid" class="miboton">Presiona</button>
<button id="otroid" class="miboton">Presiona</button>
<button id="masIds" class="miboton">Presiona</button>
    
answered by 04.11.2016 в 14:27
3

You can do it by passing this.id in the function, where this refers to the object you're clicking on.

function mandarId(id){
  alert(id);
 }
<button id="boton" onclick="mandarId(this.id)">click aquí </button>
    
answered by 04.11.2016 в 12:02
2

If you pass as a parameter, this you are passing the information of what the function calls (in this case the button) so you can get your id for example

  
  function mandarId(elem){
    alert(elem.id);
    
    }
<button id="boton" onclick="mandarId(this)"> Click </button>
    
answered by 04.11.2016 в 12:02