Alexander Hein Alexander Hein - 2 months ago 9
CSS Question

How to set data-* attribute of checked radio to class of another element using jquery?

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>




Answer

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>

Comments