Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using Button inside for each loop,created java script for click function for that button based on ID.But first button only working.other buttons not working.How to solve?

What I have tried:

Button inside for each loop
<button class="plan-button"id="demo" >Choose Plan</button>


Javascript
JavaScript
document.getElementbyId('demo').addEventListener('click', function (e) {
                handler.open();
                e.preventDefault();
  });
Posted
Updated 5-Jul-17 2:54am

1 solution

ids are supposed to be unique, if you have multiple buttons with the same id then which element do you think document.getElementbyId('demo') will refer to? It has to select only one so it is selecting the first and ignoring the rest. The easiest solution to this is to use a class to identify the elements rather than an id

<button class="plan-button demo">Choose Plan</button>


then change your js;

var el = document.getElementsByClassName("demo");
for (var i = 0; i < el.length; i++)
{
    el[i].addEventListener('click', function (e) {
        handler.open();
        e.preventDefault();
    });
}


If you can use jQuery then these things are much easier.
 
Share this answer
 
Comments
GrpSMK 5-Jul-17 9:01am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900