-1

How to validate decimal number with random value from input box using jQuery?

I have sample code below:

$("#actualWeight").on('keyup', function(e) {
  if (e.keyCode == 13) {
    var actualWeight = $("#actualWeight").val();
    var maxGrossWeight = "3.6";
    var minGrossWeight = "2.4";

    if (actualWeight > maxGrossWeight) {
      alert("More than max gross");
    } else if (actualWeight < minGrossWeight) {
      alert("Lower than min gross");
    } else {
      alert("Success");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="actualWeight" />

As you can see:
Min Gross = 2.4
Max Gross = 3.6

When I try to input 200, it show me alert Success that should be show me alert More than max gross.

You can see it on this fiddle

3
  • 1
    When you read value from DOM, its read in string format. Try converting to numeric value. Updated Fiddle Commented Jan 22, 2018 at 7:30
  • You're comparing string's, not numbers! You must to parsefloat value and set the var's maxGrossWeight and minGrossWeght without " Commented Jan 22, 2018 at 7:32
  • Possible duplicate of Using Javascript to compare two input numbers in HTML? Commented Jan 22, 2018 at 7:33

1 Answer 1

1

.val() is returning the value of input as string. Hence you are comparing string values.

You should set maxGrossWeight and minGrossWeght as float variable and parse the value of input element to float before doing the comparison :

 var actualWeight = parseFloat($("#actualWeight").val());
 var maxGrossWeight = 3.6;
 var minGrossWeight = 2.4;

Working Demo

Sign up to request clarification or add additional context in comments.

Comments

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.