Paweł Kosiński Paweł Kosiński - 4 years ago 153
Javascript Question

iCheck - set color of the siblings

I am using the jQuery library 'iCheck' for inputs and I am trying to set the color of the labels to green for those questions which were good answered. When I don't use iCheck everything works perfectly, but when I use that library, my script seems to have no effect. What am I doing wrong?

HTML document

<div class="radio" >
{% if answer.is_valid == True %}
<input type="radio" name="question-{{ question.id }}" id=" {{answer.text}}">
{% else %}
<input type="radio" name="question-{{ question.id }}" id="{{answer.text}}">
{% endif %}
<label><b>{{ answer.text }}</b></label>
</div>


JS

$('.check').click( function () {
var score = 0
var all = $('input[id^=" "]');
var checked = $('input:checked');
var good = $('input:checked[id^=" "]');

checked.siblings().css('color', 'red');
all.siblings().css('color', 'green');
good.each ( function(){
score += 1;
})

alert(score);
score = 0;
});

Answer Source

That is because icheck changes the DOM in such a way that your original input is not even visible anymore. Check the DOM browser to see that iCheck changed your

<input type="radio" name="question-{{ question.id }}" id=" {{answer.text}}">

To

<div class="iradio_flat-pink" aria-checked="false" aria-disabled="false" style="position: relative;">
<input type="radio" name="question-1" id="text" style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background-color: rgb(255, 255, 255); border: 0px; opacity: 0; background-position: initial initial; background-repeat: initial initial;">
</ins>
</div>

Or something similar.
To change the color of the element you need to use the iCheck functions instead and give it a different class:

$('#input1').iCheck({
    radioClass: 'radio-green' //or something you like.
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download