-3

How do I take the data-attribute of a checked radio button and output it inside the class attribute of a different element?

Please take a look at the example:

body{
  background: #eee;
}  

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>

<div class="box"></div>
<div class="box"></div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Alexander Hein
  • 960
  • 3
  • 19
  • 44

1 Answers1

1

You can do it using CSS only. :checked select checked radio and ~ is General sibling selectors.

input[data-color="black"]:checked ~ .box {
    background: #000;
}

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

input[data-color="black"]:checked ~ .box {
  background: #000;
}

input[data-color="white"]:checked ~ .box {
  background: #fff;
}

input[data-color="green"]:checked ~ .box {
  background: #00d300;
}
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>

<div class="box"></div>

If you want to do it using jquery, you need to get value of data-color attribute using .attr() or .data() and set it to class of .box using .addClass().

$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});

$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});
.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-color="black" id="radio1" type="radio" name="radio" checked>
<label for="radio1">Black</label>
<input data-color="white" id="radio2" type="radio" name="radio">
<label for="radio2">White</label>
<input data-color="green" id="radio3" type="radio" name="radio">
<label for="radio3">Green</label>
<div class="box"></div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • Please don't provide an answer until the OP has demonstrated that they've actually tried something. – j08691 Oct 03 '16 at 18:54