Peterson Peterson - 3 months ago 24
AngularJS Question

Adding color to label next to radio that is checked in AngularJs

I have a simple angularJs example, where actually I have to show red background to label infront of radio box that is checked. However, I cannot find selected or isChecked property in the input type="radio" selected so I can add CSS based on it.

HTML

<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">

<p ng-repeat="x in questions">
<input type="radio" id="{{x.id}}" name="{{x.name}}"><label for="{{x.id}}">{{x.value}}</label>
</p>

<script>
var app = angular.module("myApp", []);
app.controller('myCtrl',function($scope){
$scope.questions = [
{value:"red",name:"color",id:"1"},
{value:"blue",name:"color",id:"2"},
{value:"yellow",name:"color",id:"3"}
];
});
</script>

</body>
</html>


enter image description here
enter image description here

Answer

Use the :checked pseudo class to target only if the radio button is checked, then use + selector to select the label following the checked radio button:

input[type="radio"]:checked + label {
    background-color: red;
}

https://jsfiddle.net/y0fe1d7d/


It seems you are trying to have a different color for each radio button, so I'd recommend instead of giving each radio button a color in the CSS file when it's checked, give the color using inline styling (style="...") and then remove the background for the unchecked (:not(:checked)) radio buttons:

<label for="2" style="background-color: blue;">Blue</label>

input[type="radio"]:not(:checked) + label {
  background-color: transparent !important;
}

https://jsfiddle.net/y0fe1d7d/1/

Comments