1

I have order form with multiple inputs (only 4 for testing purposes), what I’m trying to achieve is that when any of these inputs are 0 or empty you are not able to submit form (basically you have to order at least 1 item). I have something similar (function checkEmpty) that I was using for a while with similar form, but as I'm very new to jQuery I have problem adopting it to jQuery and current code.

Testing jsfiddle: http://jsfiddle.net/nitadesign/97tnrepg/19/

function checkEmpty(){
var inputs =  document.forms['packaging'].getElementsByTagName('input');
var noneZeroFound = false;
for(var i=0;i< inputs.length;i++){
  var input = inputs[i]; 
  if(input.value != '0'){
     noneZeroFound = true;
     break;
  }
}
if(!noneZeroFound ){
  alert('You have to order minimum 1 product.');
  return false;
}

return true;
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Nita
  • 561
  • 5
  • 28

2 Answers2

1

Check this link

You have hidden input text in the form those are initially set like

<input type="hidden" class="pack" id="pack03-price" name="pack03-price" value="7.00">

You are getting includes hidden field in these line:

var inputs =  document.forms['packaging'].getElementsByTagName('input');

so skip checking 0 or null or emptyness on these field on form submit.

I have modified your code here:

function checkEmpty(){
 var inputs = document.forms['packaging'].querySelectorAll('input[type=text]');
 var noneZeroFound = true;
 for(var i=0;i< inputs.length;i++){
  var input = inputs[i]; 
  if((input.value != 0) & $.isNumeric(input.value)){
     noneZeroFound = false;
     break;
   }
 }
 if(noneZeroFound ){
   alert('You have to order minimum 1 product.');
   return false;
  }
  return true;
} 
sharif2008
  • 2,716
  • 3
  • 20
  • 34
  • Hm, well if input values are totaly empty then I get warning alert - that is fine. But I also want jQuery to check for 0 or null. So i have to target (check) inputs with id - pack01, pack02, etc. Inputs as pack01-price ~ are being used for calculations and display only. – Nita Sep 02 '15 at 10:10
  • Ok, Great that seem to work very good, exactlly how i want this to work. – Nita Sep 02 '15 at 10:28
  • you check this http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – sharif2008 Sep 02 '15 at 10:56
1

The above function can be revised using jQuery:

function checkEmpty(){

   var noneZeroFound = true;

     $("form#packageForm :input[type=text]").each(function(){
     var input = $(this); 

        if(input.val().length > 0) {
            noneZeroFound = false;
            return true;
        }
    });

   if(noneZeroFound){
      alert('You have to order minimum 1 product.');
      return false;
   }

   return true;
}
Sheetal
  • 1,368
  • 1
  • 9
  • 15