我正在尝试制作某种调查表。我设法动态增加 id 和 name,并且可以添加不同的答案类型。问题是当我想添加单选按钮时,它会添加 5 个。也与复选框相同。但是当尝试添加文本字段时,我希望它只添加 1,但由于我的隐藏表的结构,它添加了 5。
我可以解决这个问题吗?这是我的代码:
<html>
<head>
<title>clone table - 2.0</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
function cloneRadio() {
var aydi = $('input#gizli').val();
$table = $('table#table0').clone().attr('id', 'table' + aydi).attr(
'name', 'table' + aydi).appendTo("#div1");
$("input[type='radio']", $table).prop("name", "ans" + aydi);
$("p", $table).prop("id", "questionTXT_" + aydi);
aydi++;
$('input#gizli').val(aydi);
}
function cloneCheck() {
var aydi = $('input#gizli').val();
$table = $('table#table0').clone().attr('id', 'table' + aydi).attr(
'name', 'table' + aydi).appendTo("#div1");
$("input[type='radio']", $table).prop("name", "ans" + aydi);
$("input[type='radio']", $table).prop("type", "checkbox");
$("p", $table).prop("id", "questionTXT_" + aydi);
aydi++;
$('input#gizli').val(aydi);
}
function cloneTextField() {
var aydi = $('input#gizli').val();
$table = $('table#table0').clone().attr('id', 'table' + aydi).attr(
'name', 'table' + aydi).appendTo("#div1");
$("input[type='radio']", $table).prop("name", "ans" + aydi); // to increase name property of radiobuttons
$("input[type='radio']", $table).prop("type", "text"); // turns radiobuttons to checkboxes
$("p", $table).prop("id", "questionTXT_" + aydi);
aydi++;
$('input#gizli').val(aydi);
}
</script>
</head>
<body>
<input type="hidden" id="gizli" name="gizli" value="1" />
<br />
<br />
<!-- HIDDEN VARIABLE IS FOR INCREASING ID -->
<div id="div0" style="display: none">
<table border="1" id="table0" name="table0">
<tr>
<td colspan="5">
<p id="questionTXT_1">Question text will be here</p></td>
</tr>
<tr>
<td><input type="radio" id="A" name="ans0" /> answer1 <br />
</td>
<td><input type="radio" id="B" name="ans0" /> answer2 <br />
</td>
<td><input type="radio" id="C" name="ans0" /> answer3 <br />
</td>
<td><input type="radio" id="D" name="ans0" /> answer4 <br />
</td>
<td><input type="radio" id="E" name="ans0" /> answer5 <br />
</td>
</tr>
</table>
</div>
<div id="div1">
<!-- CLONNED TABLES WILL BE HERE -->
</div>
<div>
<input type="button" id="button1" name="clonner"
value="Add Radiobutton" onClick="cloneRadio()" /> <input
type="button" id="button1" name="clonner" value="Add Checkbox"
onClick="cloneCheck()" /> <input type="button" id="button1"
name="clonner" value="Add TextField" onClick="cloneTextField()" />
</div>
</body>
</html>