Get value (or attribute) of a toogle element

By: Emmanuel GADEK | Asked: 01/19/2023
ForumsCategory: Code HelpGet value (or attribute) of a toogle element
Emmanuel GADEK asked 1 year ago
Hi to all members,
I need to get the value (or attribute) of a toogle element with javascript.
My toogle is set up on 'off' by default.
I try a trick like this : var myvar = $("input[name='item_meta[86][]']:checked").val();
If I try to get the value on page load , I obtain 'undefined'.
If I try to get the value when the toogle is switch on on, I obtain 'yes'.
I would prefer to obtain the boolean attribute of the element (aria-checked), but I'm a noob with javascript and I don't know how to make my formula. I try differents things but I didn't get the expected value.....
Does anyone could help me ?
1 Answers
Victor Font answered 1 year ago
If you want the aria-checked label, you're targeting the wrong element. A toggle is a single element checkbox cleverly disguised as a switch with the use of multiple span tags. To get the aria-checked value of the span, you need: var myvar = $("span[aria-labelledby='field_b34jc_label']").attr('aria-checked')
Emmanuel GADEK replied 1 year ago

Hi Victor, thanks a lot for answer. It seems to be work but.... On load, the value getted is 'false'. If I switch my toogle on 'on' position, I obtain 'false' to. And if I switch back my toogle on the 'off' position, I obtain 'true' (when the toggle is positionned on the 'No' position)....

EDIT : I think it's due to a wrong test formula, I try this (in the beginnng of the test sentence) :

$('span[aria-labelledby="field_2ltf7_label"].attr('aria-checked')').change(function () {

...but it doesn't work

EDIT2 : If done some searchs on Google.... As I understand, it is not possible to have an 'onChange' listener for an attribute change.The right method will be a MutationObserver.....

Victor Font replied 1 year ago

The code I gave works perfectly in my development environment. All you had to do is change the label name. I explained earlier that a toggle is not a standard form input. The toggle is a single hidden checkbox field. The visible interactive part is a compilation of span elements. The part that you click on is a span's before pseudo element. They do not fire a change event. You could try on("click", function(){});

Without knowing how you you wrote and applied your code, it's not possible for me to help you further. Perhaps you should think about hiring a developer to take a look at your site and fix this for you.

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right