0

Here's my current code:

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy" checked="checked">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

What I'm wanting to do is add the class "working" to the parent element (form-control-switch-option) whenever the input element is checked. So, based on the example above, it should become this:

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

<div class="form-control-switch-option working">
    <input type="radio" data-value="Buy" checked="checked">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

Is there any way to do this with pure Javascript (not jQuery)?

2

1 Answer 1

1

This code will add class working immediately and by interaction.

let radios = document.querySelectorAll('input[data-value="Buy"]')
for (let i = 0; i < radios.length; i ++) {
      // if checked automatically add class 'working'
      if (radios[i].checked) {
          radios[i].parentElement.classList.add('working')
      }
      // add class 'working' by clicking
      radios[i].addEventListener('change', function () {
          this.parentElement.classList.add('working')
      })
}

You must use data-value="buy" if you want this checkbox to work. if you want to use class, you can change the querySelectorAll, for example like

document.querySelectorAll('.input-class')

the rest is still same

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.