Sandor Sandor - 1 month ago 5
CSS Question

How to change CSS with jQuery change and this

I am trying to change the text color of a selected radio button. The following code should work but for some reason it does not.

CSS:

.opts {float: left; padding-left: 5px;}


HTML:

<div class="opts"><label><input class="ws" type="radio" name="ptype" value="1">A</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="2">B</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="3">C</label></div>


jQuery

$(document).ready(function(){
$('.ws').change(function(){
var c = this.checked ? '#ff0000' : '#0099ff';
this.css('color', c);
});
});


I can replace the "this.css" with $('.opts') but then, of course, all text changes color. My problem is not being able to make the "this" work. Any help?

Answer

You need to change the color of closest .opts like following.

$('.ws').change(function() {
    $('.opts').css('color', '#0099ff'); 
    $(this).closest('.opts').css('color', '#ff0000');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="1">A</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="2">B</label></div>
<div class="opts"><label><input class="ws" type="radio" name="ptype" value="3">C</label></div>