March 10, 2012

jquery checkbox selcetion

Question by Sam Hanson

Please refer the url

http://jsfiddle.net/fnvXT/

Here while selecting the check box the corresponding row is selected. I want to change that as

only one will be highlighted at a time.

If i select check box 2 then the check box 2 will be checked and this row only be highlighted and remaining check box should unchecked and remove the highlighting.

How do i change this. Please do the needful. Thanks

Answer by TJ.

I added the following to the click handler:

$('input.high').not(this).attr('checked', null).closest('tr').css('background-color', '#fff');

See: http://jsfiddle.net/fnvXT/6/

Answer by Starx

Do not use .live() function it has been deprecated. Use .on() or .delegate() instead. Here is a simple solution to your problem

 $('.high').on('click', function(event) {          
        if ($(this).prop('checked')) {
             // if checked, reset all colors to white
             $("tr").css("background-color", "#ffffff");
             // find its parent row and change its color
             $(this).closest("tr").css("background-color", "#FFCC00");
        } else {
            // you only need to change its parent row in this case
            $(this).closest("tr").css("background-color", "#ffffff");
        }           

});

Demo

P.s. I have omitted the alternate row style in the row, to make things much simpler

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!