user1451890
user1451890

Reputation: 1095

Validating Mandatory Input Boxes Using Javascript only

I wanted to know what would be the best method to validate (to ensure that all 4 of the input boxes are not blank)?

<html>

  <head></head>

  <body>
    <input type="text" id="i1">
    <input type="text" id="i2">
    <input type="text" id="i3">
    <input type="text" id="i4">
  </body>

</html>

Upvotes: 0

Views: 145

Answers (4)

Jericho
Jericho

Reputation: 10953

HTML:

<input type="button" value="submit" onclick="submitForm()">

JavaScript :

  function submitForm()
    {
     if(validate())
      {
       alert('No blank found!!');
      }
      else
     {  alert('blank found!!');  }
    }    

    function validate()
    {
      var i1 =document.getElementById('i1').value;
      var i2 =document.getElementById('i2').value;
      var i3 =document.getElementById('i3').value;
      var i4 =document.getElementById('i4').value;
      var result = false;

      if( i1 && i2 && i3 && i4) {
         result = true;
      }
     return result;
    }

Upvotes: 0

davehale23
davehale23

Reputation: 4372

If they are all to be inputs then you can use document.getElementsByTagName

var allinputs = document.getElementsByTagName("input");
console.log(allinputs);
for (var i = 0; i < allinputs.length; i++) {
    if(allinputs[i].value.length == 0){
      alert('need to have something here');
       return;
    }
}

here is a working fiddle

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60767

My custom method, not cross-browser:

NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;

var allChecked = document.querySelectorAll('input[type=text]').every(function(el) {
    return el.value !== '';
});

if (allChecked) alert("All checked!");

The cross-browser (IE8 and above), not funny way:

var inputs = document.querySelectorAll('input[type=text]');

var allChecked = true;
for (var i = 0, len = inputs.length; i < len; i++) {
    if (inputs[i].value === '') {
        allChecked = false;
    }
}

if (allChecked) alert("All checked!");

Upvotes: 0

Tobias
Tobias

Reputation: 883

JQuery Validate is an really easy way to validate your fields. You can read more about it at their wiki:

http://docs.jquery.com/Plugins/Validation

Upvotes: 0

Related Questions