1

I think so there is a problem with for statement??

Adjusted code again, but not alert popup is all the time even if all the input fields got values?

Hello I am trying to validate a dynamic array of fields on a form:

<form onsubmit="return checkReq();">
    <input value="" type="hidden" name="slider[]" id=""/>
</form>

with the following JavaScript, but it doesn't work? Could you tell me please what I am doing wrong.

    <script language="javascript">
    function checkReq () {
        var boxes = document.getElementsByName("slider[]");
    var ret = true;
    for (var x = 0; x < boxes.length; x++) {

        if(boxes[x].value == '' || '0'){
            ret = false;
            break;
            } else {ret = true;} 

         }
   if (ret == false)
   {
     alert('Problem'); return ret;        
   }
}
    </script>

3 Answers 3

1

I think this might help.

function checkReq () {
     var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {       
    if(boxes[x].value == '' || boxes[x].value == '0'){
        ret = false;
        break;
        } else {ret = true;} 

     }    
   if (ret == false)
   {
     alert('Problem'); return ret;        
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Now alert is on all the time, even if all the fields got value in them ? strange
0

You always return after the first loop, so it doesn't go through each element (and thus redundant), is this intended?

Comments

0

Try this You are trying to compare element instead of it's value JSFIDDLE

function checkReq () {
    var boxes = document.getElementsByName("slider[]");

    for (var x = 0; x < boxes.length; x++) {

       if(boxes[x].value == '' || boxes[x].value == '0'){

            alert('Problem'); return false;

         } 
         else {return true;} 
    }
}

1 Comment

@FenixDolores press the submit button

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.