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>