1

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

1
  • Use the same class for all input fields instead of same name. Commented Sep 24, 2014 at 12:51

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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');

    }

    });

});

1 Comment

It's not working with submit button and form reload after click on button
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.