2016-03-23 48 views
1

我有一些應該顯示覆選框矩陣的JavaScript代碼。我想列出頂部的列標題,然後將行放在每個標題下有一列複選框的位置,再加上一個帶有空白標題框下的行名的左側列。我要去的看看這個頁面上:HTML表格顯示JQuery複選框而不保留數據

http://codepen.io/marclundgren/pen/hgelI

我寫了一個小提琴,幾乎工作:

https://jsfiddle.net/bv01xvdf/

的第一個問題是,我的表顯示在一個單獨的複選框從行名稱的單元格行。我檢查了我的HTML,它似乎是正確的,但我想知道我是否在某處丟失了<tr></tr>。我想補充的行名小區像這樣(見完整代碼的小提琴):

var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"]; 
for (x = 0; x < chugNames.length; x++) { 
    // Add a row for each name.        
    target.append("<tr><td>" + chugNames[x] + "</td>"); 
    for (y = 0; y < chugNames.length; y++) { 
     target.append("<td><input type=\"checkbox\" />"); 
     checkbox = $('</input>', { 
     'type': 'checkbox', 
     'data-x': chugNames[x], 
     'data-y': chugNames[y], 
     }); 
     target.append(checkbox); 
     target.append("</td>"); 
    } 
    target.append("</tr>"); 
} 

的另一個問題是數據X和數據-Y返回「未定義」當我後來訪問他們在我的「上」方法:

target.on('change', 'input:checkbox', function() { 
    var $this = $(this), 
     x = $this.data('x'), 
     y = $this.data('y'), 
     checked = $this.prop('checked'); 
    alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked); 
    }); 

當我檢查一個框,我得到「複選框更改楚格相交(undefined,undefined):true」。它應該打印像(繩索,烹飪)的東西,取決於哪個盒子被檢查過。

任何幫助將不勝感激。

回答

2

當你附加jQuery時,標籤會自動關閉。

check the jsfiddle

試試這個:

$(function() { 
    var target = $('#checkboxes'); 
    var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"]; 
    var i, x, y, checkbox, html; 
    html = "<table class=\"responsive-table-input-matrix\"><thead><tr><th></th>"; 
    // Table column headers             
    for (i = 0; i < chugNames.length; i++) { 
    html += "<th>" + chugNames[i] + "</th>"; 
    } 
    html += "</tr></thead><tbody>"; 

    for (x = 0; x < chugNames.length; x++) { 
    // Add a row for each chug.        

    html += "<tr><td>" + chugNames[x] + "</td>"; 

    for (y = 0; y < chugNames.length; y++) { 
     html += "<td>"; 
     checkbox = '<input type=checkbox '; 
     checkbox += ' data-x=' + chugNames[x] 
     checkbox += ' data-y=' + chugNames[y] 
     checkbox += '/>' 
     html += checkbox; 
     html += "</td>"; 
    } 
    html += "</tr>"; 
    } 
    html += "</tbody></table>"; 

    target.append(html).width(function() { 
    return $(this).find("input:checkbox").outerWidth() * chugNames.length 
    }); 

    target.on('change', 'input:checkbox', function() { 
    var $this = $(this), 
     x = $this.data('x'), 
     y = $this.data('y'), 
     checked = $this.prop('checked'); 
    alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked); 
    }); 

}); 
+1

謝謝!這解決了這兩個問題。一個小小的更正:chugNames [x]和chugNames [y]追加需要引號,因爲它們可能是多字。其他一切都很好 - 再次感謝。 –

1

我修好了您的jsfiddle here

爲了記錄,您有一些問題,在開始字符串中額外輸入<th></th>,額外輸出ChugName [x],並且您沒有使用attr() jQuery函數正確獲取數據屬性。

+0

HM-我試圖在b43w6ft5的小提琴,但我仍然得到同樣的錯誤。我看錯了嗎? –

+0

這是尷尬,我忘了保存:P。試試這個:https://jsfiddle.net/b43w6ft5/2/。我還用新的jsfiddle更新了答案。 – Technoh

+0

謝謝!這解決了佈局錯誤。我仍然沒有得到表格值,但是下面的答案解決了這個問題。 :)非常感謝! –