Répás
Répás

Reputation: 1820

Jquery addClass on radio box checked

I checked all the topics, but i simply don't know why my script does not work :(

<script type="text/javascript">
$('input[name=pic]').click(function() {           
    $(this).closest('ul').find(".green").removeClass("green");

    if($(this).is(':checked'))  {
        $(this).closest('ul').find("li").addClass('green');
    }
});
</script>

another script what is making the li tags

var link = document.createElement('li');
var parts = result.tbUrl.split('::');
link.innerHTML = "<label for='asd"+i+"'><img src='"+result.tbUrl+"' /></label><br /><input id='asd"+i+"' type='radio' name='pic'  value='http://"+parts[1]+"' />";
contentDiv.appendChild(link);

etc...

<ul>
    <li><input type="radio" name="pic" value="asd"/>asd</li>
    <li><input type="radio" name="pic" value="b"/>asd</li>
    <li><input type="radio" name="pic" value="ba"/>asd</li>
    <li><input type="radio" name="pic" value="bs"/>asd</li>
    <li><input type="radio" name="pic" value="bc"/>asd</li>
</ul>   

Please help me!

Upvotes: 0

Views: 1949

Answers (2)

Alistair
Alistair

Reputation: 1979

bobince is correct. You need to bind in a $(document).ready

I have made the script more efficient too.

<script type="text/javascript">
    $(document).ready(function() {
        $(':radio[name=pic]').click(function() {           
            $(this).siblings().removeClass("green").end()
           .addClass("green"); //a click always makes a radio button true, so no need to check
        });
    });
</script>

Upvotes: 0

bobince
bobince

Reputation: 536615

$('#pic') is an ID selector, and your inputs don't have IDs. You probably meant '$('input[name=pic]').

Also, you're applying the green class to the <li>, but then trying to find .green elements inside the .parents('li'). Maybe you want $(this).closest('ul') instead?

Upvotes: 2

Related Questions