我正在以
的形式动态创建输入我希望用户至少输入' n'元件。
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
function validateForm(){
var frm = document.forms['simples'];
a = parseInt(frm.elements['myInputs_1[]'].length)
var sum = parseInt(frm.elements['myInputs_1[]'].length)
if(parseInt(sum) < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
</script>
</head>
<body>
<form name="simples" action="part.php" align="center" onsubmit="return validateForm()" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
<input type="submit" value="show me what is next">
</form>
</body>
</html>
方法validateForm()
仅在数字文本框大于等于2时有效,对于0和1则不起作用。
请注意,这不是最小的例子,在真实的网站中,我有很多这样的div
收集输入在多个数组中,所以我将它们总结为:
var sum = parseInt(frm.elements['myInputs_1[]'].length) + parseInt(frm.elements['myInputs_2[]'].length) + parseInt(frm.elements['myInputs_3[]'].length)
但可能会发生很少的数组是空的。
如何检查共有至少n
个输入?
答案 0 :(得分:0)
onen = check(...)
针对每种情况都有不同的行为。
没有输入任何元素,它将是未定义的
对于1个元素,它只包含该元素,因此它没有长度
对于两个元素,它是frm.elements['myInputs_1[]']
类型的对象,它继承自RadioNodeList
并具有NodeList
属性。
所以验证表单方法更改为:
length
它有效!