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.
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.
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>
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>
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>