1

I want validate input "min" and "max" and give an error. My actual code work when I press submit button. I want validate this in live when the user complements other fields. When the user go to the next field and max

My actual code:

<!doctype html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>...</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>
<div class="error">

</div>
<form id="a" action="b.php" method="post" enctype="multipart/form-data">
    <label>
        <input type="number" name="yearMin" value="1900" min="1800" max="2299">
    </label>
    <label>
        <input type="number" name="yearMax" value="2015" min="1800" max="2299">
    </label>
    <label>
        <input type="text">
    </label>

    <button type="submit" class="button">Start</button>
</form>


<script>
    $(document).ready(
        function () {
            $("form#a").submit(
                function () {
                    var min =$('input[name^="yearMin"]').val();
                    var max =$('input[name^="yearMax"]').val();
                    if (min<max)
                    {
                        return true;
                    }
                    else
                    {
                        $('.error').text("min>max");
                        return false;
                    }

                }
            );
        }
    );

</script>


</body>
</html>

Edit:

<script>

    $("input[type=number]").on('keydown keyup',function(e) {
        var min = $('input[name^="yearMin"]').val();
        var max = $('input[name^="yearMax"]').val();
        if (min < max) {
            $('.error').text('');
            return true;
        } else {
            $('.error').text("min>max");
            return false;
        }
    });

</script>

Do I think right? text('') doesn't work.

1 Answer 1

3
$("input[type=number]").on('keydown keyup',function(e) {
  var min = $('input[name^="yearMin"]').val();
  var max = $('input[name^="yearMax"]').val();
  if (min < max) {
    return true;
  } else {
    $('.error').text("min>max");
    return false;
  }
});

The keyup event occurs when a keyboard key is released. The keydown event occurs when a keyboard key is pushed. So we will bind this event to the required element.

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

2 Comments

thanks for answer. I have one more question. When the user correct value and min<max ho to do that div will again be empty. I try "$('.error').empty();" but doesn't work.
I edit my first post. $('.error').text(''); doesn't work I think it was wrong to understand and I said not at this point

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.