views:

181

answers:

2

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!

+2  A: 

$('#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?

bobince
still not work :( - i corrected the 1st post as you said.
neduddki
Works for me, assuming the script is being executed *after* the `ul` is present in the page (ie. script below ul, or run on document ready). You may also have meant to set the green class on just `$(this).closest('li')` rather than all `li`​s (I'm not sure what exactly you're after here).
bobince
I make the LIs with an another script which create the li elements to the ul#content (called contentDiv).
neduddki
Then you will need to bind `click()` *after* those `li`​s have been added, or if you can't do that than use a `live('click')` binding.
bobince
Works correct with live click method. Thank you.
neduddki
A: 

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>
Alistair