Harald
Harald

Reputation: 289

Changing a class outside an input element

I have an input element with a checkbox:

  <input type="checkbox" id="ID1" name="ID1" checked>

Somwhere else (outside the input field), I would like to have a text, which is changing its appearence according the check status of the input element with the ID1.

Something like:

<span for id='ID1' class='Class1'>TEST</span>

How do I get a dependency between the text and the status of the input field and how is it possible to change Class1 to Class2 by checking and unchecking the checkbox? The class changes the background color of the Text. I know how to do this inside the same element. But having two different elements? Or is it possible to access the class via the ID of the input element, due to the "for" statement? I am working with javascript.

Thanks for any help!

Upvotes: 0

Views: 51

Answers (3)

j.ian.le
j.ian.le

Reputation: 207

If you want a CSS solution, you can target the input box and use the :checked selector followed by + then the adjacent element.

CSS: element+element [div + p] Selects the first <p> element that is placed immediately after <div> elements

.Class1 {
  background-color: yellow
}

#ID1:checked + .Class1 {
  background-color: skyblue
}
<input type="checkbox" id="ID1" name="ID1" checked>
<span for id='ID1' class='Class1'>TEST</span>

Check here to know more about the different CSS selectors.

Upvotes: 0

Barmar
Barmar

Reputation: 781741

Add an attribute to the checkbox with the ID of the related span.

document.querySelector("#ID1").addEventListener("click", function() {
  let rel = document.getElementById(this.getAttribute("rel"));
  if (rel) {
    if (this.checked) {
      rel.classList.add("Class1");
      rel.classList.remove("Class2");
    } else {
      rel.classList.add("Class2");
      rel.classList.remove("Class1");
    }
  }
});
.Class1 {
  background-color: red;
}

.Class2 {
  background-color: blue;
}
<input type="checkbox" id="ID1" name="ID1" checked rel="span1">
<span id="span1" class='Class1'>TEST</span>

Upvotes: 2

Aian
Aian

Reputation: 234

First : you can't/shouldn't have two element with same Id

const checkbox = document.getElementById("ID1");
const span = document.getElementById("SpanID1");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    span.innerHtml= 'TEST Checked'
  } else {
    span.innerHtml= 'TEST Unchecked'
  }
});

Upvotes: 1

Related Questions