Joe Doe
Joe Doe

Reputation: 563

Using CSS to change the content of checkbox element

input:checked ~ #value:after {
  content: attr("data-value");
}
<div>
  <label for="checkbox1">checkbox1</label>
  <input type="radio" name="check" id="checkbox1" data-value="A">
  <label for="checkbox2">checkbox2</label>
  <input type="radio" name="check" id="checkbox2" data-value="B">
</div>
<h1 id="value">
  Letters:
</h1>

Is it possible to make checked radio to add its data-value next to #value using CSS only? Make it continue as

Letters: A or Letters: B

Upvotes: 1

Views: 69

Answers (1)

EGC
EGC

Reputation: 1779

Unfortunately, this is a job for Javascript, but I can get you part of the way using Pure CSS using variables.. but this is obviously no better than having hidden divs.

:root {
  --active-contentA: 'A';
  --active-contentB: 'B';
}

input[data-value='A']:checked   ~ #value::after {
 color: red;
 content: var(--active-contentA);
}

input[data-value='B']:checked   ~ #value::after {
 color: red;
 content: var(--active-contentB);
}
  <label for="checkbox1">checkbox1</label>
  <input type="radio" name="check" id="checkbox1" data-value="A">
  <label for="checkbox2">checkbox2</label>
  <input type="radio" name="check" id="checkbox2" data-value="B">

<h1 id="value">
  Letters:
</h1>

See JSFiddle

This is the Javascript solution:

document.addEventListener('input', function (evt) {
	 var data = evt.target.getAttribute('data-value');
   var value =  document.getElementById('value');
   value.innerHTML = "Letters: " + data;
});
  <label for="checkbox1">checkbox1</label>
  <input type="radio" name="check" id="checkbox1" data-value="A">
  <label for="checkbox2">checkbox2</label>
  <input type="radio" name="check" id="checkbox2" data-value="B">

<h1 id="value">
  Letters:
</h1>

See JSFiddle


Goodluck!

Upvotes: 1

Related Questions