我有一个按钮(Add More),它在我的表单/表格中添加了新行。我想以INPUT形式添加数据自动提示。所以我尝试了以下代码。它正在工作,但只适用于第一行。它不适用于下一行。任何人都能纠正我的错误吗?您也可以在jsFiddle中查看。
<table class="table" id="dataTable" name="table">
<TD><INPUT type="text" id="tags" /></TD>
</table>
<br>
<button type="button" class="btn btn-primary" value="Add Row" onclick="addRow('dataTable')">Add More</button>
/*** Form autosuggestion **/
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
/*** Adding new row **/
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
if(i==1){newcell.innerHTML = (rowCount+1)}
else{
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "test":
newcell.childNodes[0].value="";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
答案 0 :(得分:1)
这背后的原因是因为你已经为两个文本字段传递了相同的id,而在HTML中你不能有重复的id,因为它没有意义。
这里你可以做两件事
这是fiddle给你的
HTML CODE:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table class="table" id="dataTable" name="table">
<TD>
<INPUT type="text" id="tags" class="autosuggest" />
</TD>
</table>
<br>
<button type="button" class="btn btn-primary" value="Add Row" onclick="addRow('dataTable')">
Add More
</button>
JAVASCRIPT代码:
function createAutoSuggest(element) { // Created a common function for you
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
];
$(element).autocomplete({
source: availableTags
});
}
$(function() {
createAutoSuggest($(".autosuggest"));
});
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if (i == 1) {
newcell.innerHTML = (rowCount + 1)
} else {
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "test":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
if ($(newcell).find('.autosuggest').length > 0) {
createAutoSuggest($(newcell).find('.autosuggest'));// This is the change you basically need
}
}
}
答案 1 :(得分:0)
You can use live to attach events to dynamically created textboxes.
以下是example