Search code examples
javascriptformsvalidationloopsgetelementsbyname

What is the JavaScript code for validating a form, getting elements by name, with a loop?


I have read between 5 & 7 posts, have tried to play with some of the things I have read, including jQuery, but it feels as though most posts are well beyond my understanding.

I have a form which will act as a data submission tool, so let's say 100 inputs.

I just need help checking each input, and I figured that I should be able to do it using a loop.

Goal code example:

function ()
{
    for (i = 1; i < 101 ; i++);
    var c = document.getElementsByName("Input_row_" [i]);
        if ( c = some conditionals here )
        {
            alert("message");
            return false;
            }
}

For a specific argument, one of the things I need to check is that there are no spaces in the input:

function ()
{
    for (i = 1; i < 101 ; i++);
    var c = document.getElementsByName("Input_row_" [i]);
        if ( c = "" )
        {
            alert("message");
            return false;
            }
}

Can anyone help with my syntax or get me further towards the goal?

Thanks.

-It goes without saying that I am not a programer by trade, so simple explanations would be great.


Solution

  • Method 1

    function validate() {
      for (var i = 1; i < 101 ; i++) {
        var c = document.getElementsByName("Input_row_"+i)[0].value;
        if (c == "" ) {
          alert("Please fill in #"+(i+1));
          return false;
        }
      }
      return true;
    }
    

    Method 2

    function validate(theForm) {
      var elements = theForm.elements;
      for (var i = 1; i < elements.length ; i++) ( // no need to know how many
        if (elements[i].name.indexOf("Input_row")!=-1 && elements[i].value == "" ) {
          alert("Please fill in "+elements[i].name);
          return false;
        }
      }
      return true; // allow submit
    }
    

    using <form onsubmit="return valdiate(this)"..

    Without inline code:

    window.onload=function() {
      document.getElementById("formID").onsubmit=function() {
        var elements = this.elements;
        for (var i = 1; i < elements.length ; i++) ( // no need to know how many
          if (elements[i].name.indexOf("Input_row")!=-1 && elements[i].value == "" ) {
            alert("Please fill in "+elements[i].name);
            return false;
          }
        }
        return true; // allow submit
      }
    }