2014-12-06 224 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