2014-12-06 226 views
1

我想在单击它所在的单元格时单击此按钮。此外,单元格的背景颜色也应该改变。单选按钮上的单选按钮选择

我设法让单元在点击时改变背景颜色,但我希望它也可以选择单选按钮,而不是改变背景颜色。

我是新来的JavaScript,我已经得到了的jsfiddle以下工作基于其他的例子,但无法弄清楚其余(尝试不同的东西很多

http://jsfiddle.net/Lude352m/1/

的Javascript:

$('.custom-matrix tr').click(function (e) { 
    console.log("Inside #out code"); 
    var cell = $(e.target).get(0); // This is the TD you clicked 

    //if (cell.nodeName != 'TD') cell = $(cell).closest('td').get(0); 

    // Remove the background color for all cells 
    var c = $(cell).parents('tr').children('td'); 
    $(c).each(function() { 
     $(c).removeClass('info'); 
    }); 

    // Add the background color for the clicked cell 
    $(cell).addClass("info")//.parent().siblings("tr").find("td.info").removeClass("info"); 

    var rad = $(cell).children('input'); 
    console.log("Radio: " + rad); 
    //for(var key in rad) { 
    // console.log('key: ' + key + '\n' + 'value: ' + rad[key]); 
    //} 
    $(rad).prop("checked", true) 

    // Output code to help (but will be removed once working)   
    // Empty the div '#out' (clear its contents) 
    $('#out').empty(); 
    var tr = $(this); // This is the TR (row) you clicked 
    // Loop through the TD's within the TR ?? i think? 
    // The 'i' is used as a counter but not sure how it increases each loop 
    $('td', tr).each(function (i, td) { 
     $('#out').html(

      //Cumulatively add the result of each TR (row) to the '#out' div's contents 
      $('#out').html() + '<br>' + i + ': ' + $(td).text() + (td === cell ? ' [clicked]' : '') 
     ); 
    }); 

回答

2

您的收音机输入不是您的<td>的直接子女,而是<td>中的<label>的子女,所以

var rad = $(cell).children('input'); 

需要改变,要么

var rad = $(cell).children().children('input'); 

或使用.find()

var rad = $(cell).find('input'); 
1

试试这个代码

$(cell).find("input").attr('checked', true); 

这里是一个工作Fiddle