Get aria-label of date on click

262 Views Asked by At

I am using the Mobiscroll Jquery demo and is trying to get the value of the aria-label to display in console.log. Currently I am getting null everytime I click on a date. Can anyone help me with this one please?

HTML

<div mbsc-page class="demo-date-picker">
    <div style="height:100%">
            <div id="demo"></div>
    </div>
</div>

JQuery

<script>
    
    mobiscroll.setOptions({
    locale: mobiscroll.localeEn,  // Specify language like: locale: mobiscroll.localePl or omit setting to use default
    theme: 'ios',                 // Specify theme like: theme: 'ios' or omit setting to use default
        themeVariant: 'light'     // More info about themeVariant: https://docs.mobiscroll.com/5-20-0/calendar#opt-themeVariant
});

$(function () {
    // Mobiscroll Calendar initialization
    $('#demo').mobiscroll().datepicker({
        controls: ['calendar'],   // More info about controls: https://docs.mobiscroll.com/5-20-0/calendar#opt-controls
        display: 'inline'         // Specify display mode like: display: 'bottom' or omit setting to use default
    });
});

var inputs = document.querySelectorAll("[aria-label]");
console.log(inputs.length);
for(var i = 0; i < inputs.length; i++){
inputs[i].addEventListener("click", function(e){
    console.log(this.getAttribute("aria-label"));
});     
}
</script>
1

There are 1 best solutions below

2
john Smith On

For me your code is working, it logs into console:

Friday, December 23, 2022
null
null

this is because the outer div´s are also clicked when clicking the div with the aria-label

You can select only the element you want by using it´s class:

var inputs = document.querySelectorAll(".mbsc-calendar-cell-text");
console.log(inputs.length);
for(var i = 0; i < inputs.length; i++){
    inputs[i].addEventListener("click", function(e){
        console.log(this.getAttribute("aria-label"));
    });     
}
<div class="mbsc-calendar-cell mbsc-flex-1-0-0 mbsc-calendar-day mbsc-ios mbsc-ltr mbsc- 
selected" tabindex="0">
 <div></div>
  <div class="mbsc-calendar-cell-inner mbsc-calendar-day-inner 
mbsc-ios">
   <div aria-label="Friday, December 23, 2022" role="button" aria-pressed="true" 
class="mbsc-calendar-cell-text mbsc-calendar-day-text mbsc-ios">23</div>
  </div>
</div>

you could also use other selectors, e.g:

var inputs = document.querySelectorAll("[aria-label]");

would add the click event to all elements that have an aria-label attribute