简体   繁体   中英

Why this false condition returns true?

Why when i write on the last input 6 instead of 60 and click ob the button, it returns to true thought my condition is false? How to solve this problem? Thanks in advance!

<!doctype html>
<html>

  <head>
  </head>

  <body>
    <button>get
      result</button>
    <div></div>
    <input Class="value1" value=10>
    <br>
    <br>
    <input Class="value2" value=20>
    <br>
    <br>
    <input Class="value3" value=30>
    <br>
    <br>
    <input Class="value4" value=40>
    <br>
    <br>
    <input Class="value5" value=50>
    <br>
    <br>
    <input Class="value6" value=60>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $('button').click(function() {
        var value1 = $(".value1").val();
        var value2 = $(".value2").val();
        var value3 = $(".value3").val();
        var value4 = $(".value4").val();
        var value5 = $(".value5").val();
        var value6 = $(".value6").val();

        if (value1 < value2 && value2 < value3 && value3 < value4 && value4 < value5 && value5 < value6) {

          $("div").text("true");
        } else {

          $("div").text("false");
        }

      });

    </script>
  </body>

</html>

A simple solution to your issue is convert the input box to be of type "Number", to limit the characters inputted, then convert all variables to Number.

For example:

<input  Class="value3" type="number" value=30>

$('button').click(function() {
    var value1 = Number($(".value1").val());
    var value2 = Number($(".value2").val());
    var value3 = Number($(".value3").val());
    var value4 = Number($(".value4").val());
    var value5 = Number($(".value5").val());
    var value6 = Number($(".value6").val());
});

You are comparing strings (from.value), not numbers.


You could utilise a loop with the converted values with unary plus + , like

let isIncreasing = true
let i = 1
while (i < 6 && isIncreasing) {
    isIncreasing = +$(".value" + i).val() < +$(".value" + (++i)).val();
}

if (isIncreasing) $("div").text("true");
else $("div").text("false");

By default your input value is numeric (input=30), but when you change value in your input, that become string value, and there are not implicit converstion of string to numeric.

When you get numeric value of input, use parse function like Number or parseInt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM