1

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;
  });
});
3
  • if((numofeggs < totalsm) && (size && price && farmername)) Shouldn't this be written as if((numofeggs < totalsm) && (size > 0 && price > 0 && farmername.length > 0 )) Commented Jan 1, 2017 at 13:24
  • From my program, (numoffeggs<totalsm) only excutes. Your suggestion stops working... Commented Jan 1, 2017 at 13:33
  • @Satya 0 and "" are falsy values in JS. Commented Jan 1, 2017 at 13:34

1 Answer 1

1

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 ?>;
Sign up to request clarification or add additional context in comments.

5 Comments

When I remove less than "<" sign, It's working. But the condition of (numofeggs < totalsm) is still I need to...
Where should I put this condition (numofeggs < totalsm)? In the last part?
See my updated answer, you need to convert more things to numbers.
My first program: if(numofeggs && size && price && farmername), is all working when I execute button. My second program: if((numofeggs < totalsm) && (size && price && farmername)), the "size", "price", and "farmername" are not working anymore
What do you mean by "not working"? What is the value of all the variables?

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.