0

I have a form with two input fields.

<input type="text" id="first" value="">
<input type="text" id="second" value="">

I have tried this but no success

<script>
$(function(){
    var fst=$("#first").val();
    var sec=$("#second").val();
    if (sec>fst) {
        alert("Second value should less than first value");
        return true;
    }
})
</script>

How to allow only second input values are only numbers and also less than the first input

1
  • Some code examlpes are highly appreciated! Commented Apr 16, 2017 at 22:57

1 Answer 1

2

You seem to be missing the key up event.

$(function(){
  $("#first, #second").on("keyup", function () {
    var fst=$("#first").val();
    var sec=$("#second").val();
    if (Number(sec)>Number(fst)) {
      alert("Second value should less than first value");
    return true;
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="first" value="">
<input type="text" id="second" value="">

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

2 Comments

Thanks it's working, instead of alert, the second element values should not be allowed onkeyup
You'd be better off alerting the user through a div because just not allowing it leads to very obnoxious behavior.

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.