September 14, 2011

Changing background onchange on check box: jquery

Question by danny

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?>">
    <input type="checkbox" onchange="chngbg($(this).val());" value="<?=$row->id?>" name="cbox" /></span>
</div>

Answer by gilly3

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.

Answer by Starx

If you are leaning jquery, its better to do such tasks using the following method.

$("#yourcheckboxselector").change(function() {
    id = "#d-" + id;
    $(id).addClass('bg');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!