单击单选按钮选择单选按钮

时间:2014-12-06 02:38:53

标签: javascript jquery html css

我希望在单击其所在的单元格时检查单选按钮。此外,细胞的背景颜色也应该改变。

我已设法让单元格在单击时更改背景颜色,但除了更改背景颜色外,我还希望它还选择单选按钮。

我是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 个答案:

答案 0 :(得分:2)

您的广播输入不是<td>的直接孩子,而是<label><td>的孩子,所以

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

需要更改为

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

或使用.find()

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

答案 1 :(得分:1)

试试此代码

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

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

这是一个有效的 Fiddle

相关问题