[英]Iterate through a form with JavaScript
I would like to pick a random name out of a form that i can fill with names. 我想从我可以填写姓名的表格中选择一个随机姓名。 I have a function to add more form field dynamicly. 我具有动态添加更多表单字段的功能。
Here is my code so far : 到目前为止,这是我的代码:
<form>
<div id="dynamicInput">
<input class="inputs" type="text" name="input1" placeholder='Type name' required>
<input class="inputs" type="text" name="input2" placeholder='Type name' required>
<input class="inputs" type="text" name="input3" placeholder='Type name' required>
<input class="inputs" type="text" name="input4" placeholder='Type name' required>
</div>
<input type="button" class="login login-submit" value="Add a member" onClick="addInput('dynamicInput');">
<input type="button" name="login" class="login login-submit" value="Roll the wheel!" onClick="rollIt();">
</form>
My Javascript functions are as follows : 我的Javascript函数如下:
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input class='inputs' type='text' name='input" + counter + "' placeholder='Type name' >";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function rollIt() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
}
I have two questions : 我有两个问题:
My friends are laughin at my face because of the onClick usage. 由于onClick的使用,我的朋友们都嘲笑我的脸。 Is it that bad ? 那样不好吗?
How could i store the form values in a list ? 我如何将表单值存储在列表中? I tried to show them with the rollIt function with no success. 我试图用rollIt函数向他们展示没有成功。
maybe something like this: 也许是这样的:
function randomName(){
var inputs = document.getElementsByTagName('input');
randomName = document.querySelector('[name="input'+(Math.floor(Math.random() * inputs.length) + 1)+'" ]').value;
return randomname;
}
this simply returns random value of input[name="input+x"] 这只是返回input [name =“ input + x”]的随机值
ps: document.querySelector is not supported by all platforms so to be sure just add a getElementByAttribute function you can get everywhere around the web ps:并非所有平台都支持document.querySelector,因此请确保只需添加一个getElementByAttribute函数,您就可以在网络上随处可见
About your question : My friends are laughin at my face because of the onClick usage. 关于您的问题: 由于onClick的使用,我的朋友们都嘲笑我。 Is it that bad ? 这样不好吗?
In fact, don't put inline javascript is better for some reasons : 实际上,出于某些原因,不要将内联javascript更好:
So try to avoid those inline onclick usages. 因此,请尝试避免使用那些内联onclick用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.