Changing background onchange on check box: jquery
I am new to jquery and i am having problem i want to change background color of parent div when i click at checkbox
Please Advice
Thank You
<script type="text/javascript">
function chngbg(id){
id2 = "d-" + id;
$(id2).addClass('bg');
}
</script>
<div class="dataDiv" id="d-<?=$row->id?>">
<in开发者_如何学JAVAput type="checkbox" onchange="chngbg($(this).val());" value="<?=$row->id?>" name="cbox" /></span>
</div>
An id selector needs to have a leading #
character.
var id2 = "#d-" + id;
If you are leaning jquery, its better to do such tasks using the following method.
$("#yourcheckboxselector").change(function() {
id = "#d-" + id;
$(id).addClass('bg');
});
You are missing the #
in your id selector.
function chngbg (id) {
id2 = "#d-" + id;
$(id2).addClass('bg');
}
By the way, you've got an extra </span>
that seems like it doesn't belong.
You'll just need to clean up the layout, i added a lot of comments since you said you were new. This will do what you want though.
$(function(){ //all of this will execute on page load
$("[name='cbox']").click(function(event){ //this will bind to the click handler for your checkbox
$(this) // this equals the checkbox that was clicked
.parent() //this traverses up to the parent div
.addClass("bg"); //this adds the class
});
});
If you want it to be similar to your example, you could set a php var of $ids to an array, then add the ids to it:
<?
$ids[] = $row->id;
?>
<div class="dataDiv" id="d-<?= $row->id; ?>">
<input type="checkbox" value="<?= $row->id; ?>" name="cbox" />
</div>
Then, in your script, you could do:
<script>
$(document).ready(function() {
$('<?= '#' . implode(',#', $ids); ?>').change(function() {
$(this).closest('div').addClass('bg');
});
});
</script>
Or if you don't want to use the $ids var you can select via class name (best way) or where name='cbox', or something else.
精彩评论