Aod Ren
Aod Ren

Reputation: 679

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 :

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 :

Upvotes: 1

Views: 55

Answers (2)

Prechan
Prechan

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 :

  • Separate presentation from controller layer. (HTML / JavaScript).
  • So maintainability is improved because of the first reason for you and mates.
  • Better way to debug your code. You don't have to check multiples files, only .js
  • According to this post, you can't put inline js in cache and so improve your user experience.

So try to avoid those inline onclick usages.

Upvotes: 0

john Smith
john Smith

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

Related Questions