dynamic buttons - get the ID of the button pressed from javascript

0

I have a view, which dynamically creates several elements of type Button in the following way:

@foreach (PacienteSeleccionDispensarDto paciente in @Model)
{
<input type="button" name="btnPaciente"             id="[email protected]" 
value="@paciente.NombrePaciente" onclick="fnProcesaPaciente()" />
}

in the event onclick , I put the function fnProcesaPaciente , in which I need to rescue the id of the button that the user pressed, and was trying in the following way

 var PacienteId = $(this.data("id"));

but apparently this does not work, because the buttons are created in a partial view, not in the main view (I do not know if this will have an impact).

How can I know the ID of the button pressed?

Greetings

    
asked by Luis Gabriel Fabres 08.04.2017 в 01:34
source

1 answer

5

If you add a function to the onClick of the button, send it as a parameter to that button so that it will be easier to capture the value from the function using the reserved word this

<input type="button" name="btnPaciente"         id="[email protected]" 
value="@paciente.NombrePaciente" onclick="fnProcesaPaciente(this)" />

Then from its function to capture the value, accessing the attribute id of comp that would be the botón that occurred click

function fnProcesaPaciente(comp){
  let id = comp.id;
  console.log(id);
}

JQUERY

Using the on (event, component, function) method so that I heard the click event that occurs in all controls Input of type=button , if the event occurs we access the id of the element by the reserved word this that refers to the control that was given click and property id .

$(function() {
 $(document).on('click', 'input[type="button"]', function(event) {
    let id = this.id;
	console.log("Se presionó el Boton con Id :"+ id)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" name="e" value="e" id="idn1">
<input type="button" name="e" value="e" id="idn2">
<input type="button" name="e" value="e" id="idn3">
<input type="button" name="e" value="e" id="idn4">
    
answered by 08.04.2017 в 01:46