Vladimir Štus
Vladimir Štus

Reputation: 217

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs

<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>

function validation(){

    var x = document.forms["form"]["name"].value;
    if(x ==='')
    {
       $("#warning").html("Morate uneti vrednost!").css('color','red');
    return false;
    }
    else
    {
        return true;
    }

}

for example if enter only one field, validation will work, and i want to check all fields

Upvotes: 1

Views: 3996

Answers (3)

Johan Karlsson
Johan Karlsson

Reputation: 6476

Try this:

function validate(){
    var error = 0;
    $.each( $("input[name='name[]']"), function(index,value){
        if( value.value.length == 0){
            $("#warning").html("Morate uneti vrednost!").css('color','red');   
            error = 1;
            return;
        }
    });
    if(!error){
        $("#warning").html(""); 
    }
}

Check it out here: jsFiddle

Upvotes: 0

SubjectCurio
SubjectCurio

Reputation: 4872

Using just JS you could do something like

<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>

<script type="text/javascript">
  function validate() {
      var inputs = document.getElementsByTagName("input");
      var empty_inputs = 0;
      for(var i = 0; i < inputs.length; i++) {
          if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
              if (inputs[i].value == '') {
                  empty_inputs++;
                  console.log('Input ' + i + ' is empty!');
              }
          }
      }

      if (empty_inputs == 0) {
          console.log('All inputs have a value');
      }
  }
</script>

Upvotes: 2

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

You have tagged jquery, so I have given something which works in jquery http://jsfiddle.net/8uwo6fjz/1/

$("#validate").click(function(){

    var x = $("input[name='name[]']")
    $(x).each(function(key,val){
    if($(val).val().length<=0)
    {
       $("#warning").html("Morate uneti vrednost!").css('color','red');

    }

    });

});

Upvotes: 0

Related Questions