I am trying to add a CSS class to a radio button based on which radio button is selected.
$("input[type=radio][name=align]").on('change', function() {
var radVal = $("input[type=radio][name=align]").val();
if (radVal == 'center') {
$(".tlt1").addClass('centerCssClass').change();
$(".tlt1").removeClass('topCssClass').change();
} else if (radVal == 'top') {
$(".tlt1").addClass('topCssClass').change();
$(".tlt1").removeClass('centerCssClass').change();
}
});
.centerCssClass {
background-color: blue;
}
.topCssClass {
background-color: red;
}
.tlt1 {
float: left;
height: 300px;
width: 300px;
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1"></div>
You have two issues here. Firstly the selector you're retrieving the value from is incorrect. You should use the this
reference to get the value from the clicked radio button.
Secondly you need to make the CSS classes more specific so that they override the original background-color
setting of .tlt1
. Try this:
var $tlt = $(".tlt1");
$("input[type=radio][name=align]").on('change', function() {
var radVal = $(this).val();
if (radVal == 'center') {
$tlt.addClass('centerCssClass').removeClass('topCssClass');
} else if (radVal == 'top') {
$tlt.addClass('topCssClass').removeClass('centerCssClass')
}
});
.tlt1 {
float: left;
height: 300px;
width: 300px;
background-color: orange;
}
.tlt1.centerCssClass {
background-color: blue;
}
.tlt1.topCssClass {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1"></div>
Note that you also don't need to trigger the change()
event on the div
elements as it's redundant.
You need to use :checked
selector to get selected radio button value and slightly change the CSS class declaration to override the background-color
$("input[type=radio][name=align]").on('change', function() {
var radVal = $("input[type=radio][name=align]:checked").val();
if (radVal == 'center') {
$(".tlt1").addClass('centerCssClass').removeClass('topCssClass');
} else if (radVal == 'top') {
$(".tlt1").addClass('topCssClass').removeClass('centerCssClass');
}
});
.tlt1.centerCssClass {
background-color: blue;
}
.tlt1.topCssClass {
background-color: red;
}
.tlt1 {
float: left;
height: 300px;
width: 300px;
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1">tlt1</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With