简体   繁体   中英

How to check all input boxes are not empty or equal to 0?

I have a form with many input boxes. I want to make a function that will go through each box and determine if any of the boxes are 0 or empty.

The user only needs to fill one one of the input boxes. If they fill all of them, that is fine too. But one is the minimum requirement. Otherwise an error alert should appear.

<form method="POST" onsubmit="return checkInputs()" name="inputData" id="inputData">

  Socks <input class="text-center" value="0" type="text" id="socks" name="socks">

  Underwear <input class="text-center" value="0" type="text" id="underwear" name="underwear">

  Ties <input class="text-center" value="0" type="text" id="ties" name="ties">

  Pants <input class="text-center" value="0" type="text" id="pants" name="pants">


  <a href="#" onClick="checkInputs()"> Save</a>

</form>

And my JS

function checkInputs() {

    var flag=0;

    $("form#inputData :input[type=text]").each(function(){
        var input = $(this); 
        if(input.val() > 0) {
          // all good
        } else { 
            flag=1; 
        }
    });

    if(flag==1){
        alert('Error!');
    } else {
        alert('Thanks!');
    }

}

My codePen is http://codepen.io/anon/pen/mPmoma

try something like this:

function checkInputs() {

    var flag=0;
  var result = new Array();

    $("form#inputData :input[type=text]").each(function(){
        var input = $(this); 
        if(input.val() > 0 && input.val() !== '' ) {
            result.push(input.val());
        } 
    });

    if(result.length > 0){
        alert('thanks')
    } else {
        alert('error!'); 
    }

}

for simpler code, you can also use jquery selectors:

$('input[type=text]:not([value=""],[value=0])')

*Edit: with a conditional:

var len = $('input[type=text]:not([value=""],[value=0])').length;
if(len>0) alert('thanks');
else alert('error!');

As pointed out by the other answers, the critical flaw in your design is that the $('.alert-danger') is modified for each iteration of .each() . Below is one possible solution with the explanation to follow:

 function checkInputs() { $('.alert-danger').show(); $("form#inputData :input[type=text]").each(function() { var input = $(this); if (parseInt(input.val(), 10) > 0) { $('.alert-danger').hide(); return false; } }); if($('.alert-danger').is(':visible')) { alert("Danger!"); } else { alert("Thanks!"); } } 
 body { padding: 0; margin: 0; } .alert-danger { color: #a94442; background: #f2dede; border-bottom: 1px solid #ebccd1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" onsubmit="return checkInputs()" name="inputData" id="inputData"> <div style="display:none" class="alert-danger">You need enter at least 1 quantity for any or all of these choices. </div> <br /><br /> <input class="text-center" value="0" type="text" id="socks" name="socks"><br /> <input class="text-center" value="0" type="text" id="underwear" name="underwear"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <br /><br /> <a href="#" onClick="checkInputs()"> Save</a> </form> 

You'll notice a few changes in the above code example from the one you provided. First, I removed the flag variable. By calling .show() and .hide() at the appropriate times, we can utilize the .alert-danger 's visibile presence as the key as to whether or not we show the error or hide the error.

The second change is that we're parsing the input box values using parseInt(input.val(), 10) before checking to see if the value is greater than 0 . By using the type conversion properties that parseInt() provides, we can filter out irrelevant content. For example the letter "a" will not validate as a legitimate value since its non numeric since parseInt("a", 10) = NaN and NaN > 0 .

Finally, since you noted that only one value had to be set for validation to accept the input, I've added return false; to the .each() loop. With this line, the loop will short circuit as soon as one value validates correctly.

The first issue has been clearly explained by others - iteration.

The second issue . You're using a link to trigger the function. Do not forget that the default action of a link is to follow the link, even if it is to the same page or '#' in your case, which may cause the page to reload. Use event.preventDefault(); to prevent the default action.

Thirdly , the alert() function s not a good debugging tool. The page refreshes as soon as you click ok on the alert and the page resets.

 $('.save').on('click', function(e) { e.preventDefault() var ok = $(this).closest('form').find(':text.text-center').filter(function() { return $(this).val() > 0; }); if( ok.length ) { $('.alert-danger').slideUp(); $('.out').text('Thanks!'); } else { $('.alert-danger').slideDown(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" name="inputData" id="inputData"> <div style="display:none" class="alert-danger">You need enter at least 1 quantity for any or all of these choices. </div> <br /><br /> <input class="text-center" value="0" type="text" id="socks" name="socks"><br /> <input class="text-center" value="0" type="text" id="underwear" name="underwear"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <input class="text-center" value="0" type="text" id="ties" name="ties"><br /> <br /><br /> <a href="#" class="save"> Save</a> <div class="out"></div> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM