Reputation: 679
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 :
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. 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.
Upvotes: 1
Views: 55
Reputation: 71
About your question : My friends are laughin at my face because of the onClick usage. Is it that bad ?
In fact, don't put inline javascript is better for some reasons :
So try to avoid those inline onclick usages.
Upvotes: 0
Reputation: 17936
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"]
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
Upvotes: 1