Emerge Paul Faller
Emerge Paul Faller

Reputation: 23

Implementing if-else condition inside ajax script

I'm having a problem with this condition. The "(numofeggs < totalsm)" in the condition is only executes. Otherwise, all variables (except "numofeggs < totalsm") are not functional. Is there any ways things to do?

$(document).ready(function() {
  displayDataSM();
  displayTotaleggs();
  $("#btn-input").click(function() {
    var numofeggs = $("#numofeggs").val();
    var size = $("#size").val();
    var price = $("#price").val();
    var farmername = $("#farmername").val();
    var totalsm = "<?php echo $totalSmall ?>";

    if ((numofeggs < totalsm) && (size && price && farmername)) {
      $.ajax({
        url: "ajaxeggsout.php",
        type: "POST",
        async: false,
        data: {
          "btn-input": 1,
          "numofeggs": numofeggs,
          "size": size,
          "price": price,
          "farmername": farmername
        },
        success: function(data) {
          displayDataSM();
          displayTotaleggs();
          $("#numofeggs").val('');
        }
      })
    }
    return false;
  });
});

Upvotes: 1

Views: 150

Answers (1)

Barmar
Barmar

Reputation: 780818

You need to convert your inputs to numbers. The number 0 is falsy, but the string "0" is truthy. And when you do comparison with <, numbers work differently than strings (e.g. 5 < 12 is true, but "5" < "12" is false).

For the inputs, use Number() to convert them to numbers. And for the variable that comes from PHP, don't put it in quotes.

So do:

var numofeggs = Number($("#numofeggs").val());
var size = Number($("#size").val());
var price = Number($("#price").val());
var farmername = $("#farmername").val();
var totalsm = <?php echo $totalSmall ?>;

Upvotes: 1

Related Questions