我有一个HTML表单,可以动态添加表单。我对单选按钮有问题,它只能选择一个选项(即使单选按钮位于不同的标签中)。我搜索解决方案,一种解决方案是更改单选按钮的名称。还有其他方法吗?因为我的其他输入都使用相同的名称,并且在提交表单时,所有输入都可以收集在一个数组中。
如果没有其他方法,如何更改克隆元素的单选按钮名称?
这是我的代码:
app.get('/form', function (req, res) {
var html='';
html += `<head>
<style>
.formset {
border-style: solid;
border-width: 1px;
}
</style>
<script>
var id=1
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
document.getElementById("divParent").appendChild(cln);
}
</script>
</head>`;
html +="<body>";
html += "<p>Click the button to make a BUTTON element with text.</p>";
html += '<button onclick="myFunction()">Add form</button>';
html += "<form action='/thank' method='post' name='form1'>";
html += "<div id='divParent'>";
html += "<div id='div1' name='formset' class='formset'>";
html += "<p>Name: <input type= 'text' name='name'></p>";
html += "<p>Sex: Male <input type='radio' name='gender' value='male'>"
html += " Female <input type='radio' name='gender' value='female'></p>"
html += "<p>Email: <input type='text' name='email'></p>";
html += "<p>Address:<input type='text' name='address'></p>";
html += "<p>Mobile number:<input type='text' name='mobilno'></p>";
html += "</div>";
html += "</div>";
html += "<input id='input1' type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);
});
以及处理表单的代码:
app.post('/thank', urlencodedParser, function (req, res){
var reply='';
reply += "<br>Array length is : " + req.body.name.length;
reply += "<br>Your name is : " + req.body.name;
reply += "<br>Sex is : " + req.body.gender;
reply += "<br>Your E-mail id is : " + req.body.email;
reply += "<br>Your address is : " + req.body.address;
reply += "<br>Your mobile number is : " + req.body.mobilno;
res.send(reply);
});
答案 0 :(得分:2)
我认为您需要更改单选输入的名称,将类添加到单选以使其可以通过getElementsByClassName找到。
html += "<p>Sex: Male <input type='radio' class='gender' name='gender' value='male'>"
html += " Female <input type='radio' class='gender' name='gender' value='female'></p>"
//change the name, add id to the end
function changeName(element, id) {
var x = element.getElementsByClassName("gender");
var i;
for (i = 0; i < x.length; i++) {
x[i].name += id;
}
}
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
//change radio id
changeName(cln, id);
document.getElementById("divParent").appendChild(cln);
}