Script is not running

I had add 2 values from Text Boxes and check the value if >1 then validate another one text box using the following code;

var qty1 = parseFloat(document.getElementById("txtqty1").value);
var qty2 = parseFloat(document.getElementById("txtqty2").value);
var totqty = qty1 + qty2;

if (totqty > 1) {
  var totamtpaid = parseFloat(document.getElementById("txttotamtpaid").value);
  if (totamtpaid < 1 || totamtpaid.value == "" || totamtpaid.value == "0") {
    alert("Enter Total amount paid ");
    totamtpaid.focus();
    return false;
  }
  var avgprice = parseFloat(document.getElementById("txtavgprice").value);
  if (avgprice < 1 || avgprice.value == "" || avgprice.value == "0") {
    alert("Enter Average price paid ");
    avgprice.focus();
    return false;
  }
}


But it is not running. Where I did the mistake? please help…

Hi there gunapriya,

try it like this…

<script>
(function() {
   'use strict';
   var qty1 = document.getElementById('txtqty1').value;
   var qty2 = document.getElementById('txtqty2').value;
   var totamtpaid = document.getElementById('txttotamtpaid');
   var avgprice = document.getElementById('txtavgprice');
   var totqty = qty1 + qty2;

     if(totqty > 1) {
         if(totamtpaid.value < 1 || totamtpaid.value === '' || totamtpaid.value === 0 ) {
            alert( 'Enter Total amount paid ' );
            totamtpaid.focus();
            return false;
         }
         if(avgprice.value < 1 || avgprice.value === '' || avgprice.value === 0 ) {
            alert( 'Enter Average price paid ' );
            avgprice.focus();
            return false;
         }
      }
}());
</script>

coothead

By the time the script is executing, the values of #txtqty1 and #txtqty2 will be just empty strings (unless you provided a default value in the markup). To run that check when the user actually entered some values, you’ll have to add event listeners to do so:

var txtqty1 = document.getElementById('txtqty1')
var txtqty2 = document.getElementById('txtqty1')

var validateInput = function () {
  var  qty1 = parseFloat(txtqty1).value
  var  qty2 = parseFloat(txtqty2).value
  // etc.
}

txtqty1.addEventListener('change', validateInput)
txtqty2.addEventListener('change', validateInput)

PS: If you’re planning to keep those alerts, you might just add an event listener to a submit button or something – otherwise the constant modal messages would be rather annoying.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.