Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript event listener get value

Hi I am updating a website someone else made.
I have a calendar and each date in the calendar has the same values

<a class="bkiavanae" href="#" id="selectiondate" data-dn="02 May 2024" data-ct="1-a">2<p style="font-size: 10px">£110</p></a>

All have the same class and id value.
I have placed an event listening to the onClick for any clicks on the class bkiavanae which is working fine.

But I need the on click to capture the value of the data-dn value. So in this example need it to return 02 May 2024

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 var calenderSelection = document.getElementsByClassName("bkiavanae");
   for (var i = 0; i < calenderSelection.length ; i++) {
    calenderSelection[i].addEventListener("click",
     function (event) {
         event.preventDefault();
               //alert("hello");
     },
     false);

}

>Solution :

Use event.target.getAttribute to retrieve the value of the data-dn attribute:

var calendarSelection = document.getElementsByClassName("bkiavanae");

for (var i = 0; i < calendarSelection.length; i++) {
  calendarSelection[i].addEventListener("click", function (event) {
    event.preventDefault();
    const dateValue = event.target.getAttribute("data-dn");
    alert(dateValue);
  }, false);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading