user2208768 user2208768 - 2 months ago 9
Javascript Question

Jquery Select Radio Button on TD click, while adding class to active TD

I'm looking to create a grid that allows users to select the cell they want, which will select a radio button. Ideally I'll be able to hide the radio buttons and have there be a class added to the active cell so the user knows which one they've selected. The problem I'm having now is that while the radio button is selected when the user clicks on the cell, the class is only added when the actual radio button is clicked. Also, it doesn't always remove the class when another box is clicked.

This is the script being used to add the class:

$(document).ready(function() {
$("td input").change(function () {
var $this = $(this);
var td = $this.parent();
td.siblings().filter(function() {
return !!$(this).find('input[name="'+$this.attr('name')+'"]:radio').length;
}).removeClass('activecell');
if(this.checked) {
td.addClass('activecell');
}
});
});


And a demo of the page
http://jsfiddle.net/VU6dN/

Any help would be appreciated.

Answer

Put the click handler on the cell instead of the radio button, select the radio button when the cell is clicked and assign a CSS class to the radio button that hides it. Something like the following. Also, here's an updated fiddle that works.

$('td').click(function() {
    var $cell = $(this);
    $('td.activecell').removeClass('activecell');
    $cell.addClass('activecell');
    $cell.children('input').attr('checked', 'checked');
});
Comments