Radio button into images created dynamically
I want to change the checked radio btn by clicking on an image who is created dynamically. This is the PHP generating my image:
<?php if($subject_list){
foreach ($subject_list as $item):?>
<input type="radio" name="subjectagendaactivity" value="male" />
<img src="/static/images/school/students/subjects/island/island_<?php echo $item['id'];?>_agenda.png"/>
<?php endforeach;}?>
So my images are generated like this and this is the code i made in JQuery to be able to change the .cheked:
$(this).click(function ()开发者_运维问答 {
$('input:radio[name=subjectagendaactivity]')[0].checked = true;
});
I need to change the [0] into a $(this) or something like this so my radio btn is checked when i click on the right image.
Would something like this work for you?: http://jsfiddle.net/FsshJ/ The only downside is that it requires both the img
and the input
to have IDs. However, you could change it to something else if you wanted/needed to.
Try this:
$(this).click(function () {
$('input:radio[name=subjectagendaactivity]').attr("checked", true);
});
$(this).click(checkIt($(this)));
// Elsewhere
function checkIt(rBtn) {
rBtn.checked = true;
}
Assuming the checkbox you want to check is always the element before the image you're clicking on:
$('img').click(function () {
var $check = $(this).prev(':checkbox');
if($check.is(':checked'){ // Already checked? Uncheck it!
$check.removeAttr('checked');
}
else{
$check.attr('checked','checked');
}
});
Take a look at jQuery's traversal methods; you should be able to find one that will allow you to grab your checkboxes by convention.
try this:
$('input:radio[name=subjectagendaactivity]').each(function(index) {
if(index == 0)
{
$(this).attr("checked","checked");
return;
}
});
精彩评论