-2

I tried to insert a class to a parent element. I want to insert a border to parent when the input is checked and is not checked to remove the class.

Thank you

if ($('.input.colorSpanInput').prop("checked")) {
  $('.colorSpan').addClass('selected');
}
.selected {
  border: 2px #ccc solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="colorSpan">
        <input type="radio" name="color" class="colorSpanInput" checked>
  </span>
connexo
  • 41,035
  • 12
  • 60
  • 87
Aggz
  • 39
  • 1
  • 1
  • 3

1 Answers1

0

You don't need jQuery for this, at all. Here's a vanilla Javascript solution for your problem, with comments in the code explaining what's going on.

// get a list of all .colorSpanInput elements in the page
const colorSpanInputs = document.querySelectorAll('.colorSpanInput');

// iterate over the list and add a change listener to each of them
// toggling the selected class on the parent element depending on the checked state
for (const colorSpanInput of colorSpanInputs) {
  // set correct initial state
  colorSpanInput.parentElement.classList[colorSpanInput.checked ? 'add' : 'remove']('selected');
  // and add the change listener so things adjust dynamically
  colorSpanInput.addEventListener('change', function() {
    // because checking one radio button will uncheck all others with the same name
    // and because that unchecking won't trigger a change event on those
    // with every change event occurring we need to make sure each radio
    // is evaluated again, otherwise the .selected class never gets removed once on:
    for (const colorSpanInput of colorSpanInputs) {       
      colorSpanInput.parentElement.classList[colorSpanInput.checked ? 'add' : 'remove']('selected');
    }
  })
}
.selected {
  border: 2px #ccc solid;
}
<span class="colorSpan">
  <input type="radio" name="color" class="colorSpanInput" checked />
</span>
<hr />
<span class="colorSpan">
  <input type="radio" name="color" class="colorSpanInput" />
</span>
<hr />
<span class="colorSpan">
  <input type="radio" name="color" class="colorSpanInput" />
</span>
<hr />
<span class="colorSpan">
  <input type="radio" name="color" class="colorSpanInput" />
</span>

This will work for any number of .colorSpanInput elements, and change only the style of the parent element.

connexo
  • 41,035
  • 12
  • 60
  • 87