Home > Net >  Click on multiple elements with same ID
Click on multiple elements with same ID

Time:06-01

My JSP generates two buttons with same id, but when I click on it I want just the one I click on to change style. This is my JSPcode:

<%for(MetodoPagamentoBean m : result){%>    
  <button  id="metodo-pagamento-scelto">
    <span><ion-icon name="card"></ion-icon><ion-icon  name="checkmark-circle" id="carta-scelta" style="display:none;"></ion-icon></span>
    <span><b>Numero:</b> <%= "XXXX XXXX XXXX "   m.getNumeroCarta().substring(m.getNumeroCarta().length()-4) %></span>
    <span><b>Intestatario:</b> <%= m.getNomeIntestatario()%></span>
  </button>
 <%} %>

while my jQuery is:

$("#metodo-pagamento-scelto").click(function(){
  $("#carta-scelta").show();
  $("#metodo-pagamento-scelto").css("border", "2px solid green");
});

How can I correct this behavior?

CodePudding user response:

  • Fix your JSP. Creating multiple elements with the same ID is clear sign of poor programming and markup habits. Use classes instead:
  • Don't use .css() when not necessary. Use jQuery's .toggleClass() or addClass() instead.
  • Use this in jQuery like $(this) to refer to the event currentTarget Element
$(".metodo-pagamento-scelto")     // Use classes
  .on("click", function() {       // Use the .on() Method
    $("#carta-scelta").show();
    $(this).addClass("active");   // Use $(this) to refer to the clicked button
  });

CSS:

.metodo-pagamento-scelto.active {
  border: 2px solid green;
}

CodePudding user response:

You can do this when an individual button is clicked

html:

<button onclick="myfunction()">button</button>

js:

function myfunction() {

}

as allways hope this helps and currently I'm on a commenting ban for some reason so I would have to edit this doc to reply if you need help.

  • Related