Question

Here is a simple "addClass" function that I am trying but it does not work. Should be a simple thing sitting somewhere in the code ))). The text should change colour based on user's selection in radioGroup1 in here http://jsfiddle.net/PatrickObrian/gdb5t/

HTML

<div class="test">Information that I want to be coloured</div>
<div>
   <label><input type="radio" id="A" name="RadioGroup1" value="Y">Yes</label>
    <br>
   <label><input type="radio" id="B" name="RadioGroup1" value="N">No</label>
</div>

JS

<script>
 $('input[type=radio][name=RadioGroup1]').change(function(){
 if (this.value == 'Y') {
        $('.test').addClass("classGreen");
}
else if (this.value == 'N') {
        $('.test').addClass("classRed");
}
    }


</script>

CSS

.classGreen {color: green} 
.test {font-size:24px}
.classRed {color: red}

Thanks in advance!

Was it helpful?

Solution 2

You should remove other color class name, and also your check the click event:

$('input[type=radio][name=RadioGroup1]').click(function(){
    if (this.value == 'Y') {
       $('.test').removeClass("classRed").addClass("classGreen");
    }
    else if (this.value == 'N') {
       $('.test').removeClass("classGreen").addClass("classRed");
    }
});

and also I don't know but this worked for CSS:

<style type="text/css">
.test { font-size:24px }
.classRed { color: red }
.classGreen { color: green } 
</style>

:)

OTHER TIPS

You need to remove the previous associated class, and then add the new class.

jQuery(function () {
    $('input[type=radio][name=RadioGroup1]').change(function () {
        if (this.value == 'Y') {
            $('.test').removeClass('classRed').addClass("classGreen");
        } else if (this.value == 'N') {
            $('.test').removeClass('classGreen').addClass("classRed");
        }
    })
})

Demo: Fiddle

Also in the fiddle there were many other problem

  • jQuery was not included
  • the style part was not proper
  • there were syntax errors

A shorter way is to use toggleClass()

jQuery(function () {
    $('input[type=radio][name=RadioGroup1]').change(function () {
        $('.test').toggleClass("classGreen", this.value == 'Y');
        $('.test').toggleClass("classRed", this.value != 'Y');
    })
})

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top