0

I'm using jQuery to compare the values of two input fields. One is the "maximum" value and one is the "minimum" value. The objective of the validation is to check if the minimum value is greater than the maximum value.

My logic is almost working but with a small bug. It is triggered with an onBlur event (on one of the tested fields) and once the pop-up alert displays, the user can click anywhere else, and the test is no longer run (thus allowing the minimum value to be greater than the maximum.

Here is the jQuery:

//Function to validate if maximum benefit value is more the minimum benefit value
function minMaxValues(){
    var maxAmt = ($('#maxAmount').val());
    var minAmt = ($('#minAmount').val());
    if ((minAmt != '') && (maxAmt != '') && (maxAmt < minAmt)){
        alert('The maximum benefit amount must be larger than the minimum amount.');
        return false;
    } else {
        return true;
    } //end maxAmt minAmt comparison
}//end minMaxValues function

The HTML:

<label>Maximum Benefit Amount:</label>
    <input type="text" name="benefit_max_amount" value="" onBlur="minMaxValues();" id="maxAmount">
<label>Minimum Benefit Amount</label>
    <input type="text" name="benefit_min_amount" value="" onBlur="minMaxValues();" id="minAmount">

How do I get jQuery to look at the page all the time and compare the values so that the condition can never be true without an alert (warning)?

EDIT: I should state that I'm looking for something modular, so that it can be used in other locations (thereby allowing this to go into an external js file, and not execute on page load, but only by calling a function.)

2 Answers 2

5

Delegate the check using jQuery on function so that it will check whenever the value changes in the inputs.

$('#container').on('change', 'input[name="benefit_max_amount"], input[name="benefit_min_amount"]', function(){
  return minMaxValues();
});
  • container is the element used for demonstration purpose but you should use the one which contain the input elements on your page.

And your html need not contain any onblur events

<label>Maximum Benefit Amount:</label>
<input type="text" name="benefit_max_amount" value="" id="maxAmount">

<label>Minimum Benefit Amount</label>
<input type="text" name="benefit_min_amount" value="" id="minAmount">

Your JavaScript function (changed as mentioned in comments to parse integer values)

function minMaxValues(){

    var maxAmt = ($('#maxAmount').val());
    var minAmt = ($('#minAmount').val());

    if ((minAmt != '') && (maxAmt != '')){
      try{
        maxAmt = parseInt(maxAmt);
        minAmt = parseInt(minAmt);

        if(maxAmt < minAmt) {
          alert('The maximum benefit amount must be larger than the minimum amount.');
          return false;
        }
      }catch(e){
        return false;
      }
    } //end maxAmt minAmt comparison

    return true;

}//end minMaxValues function

Finally the fiddle:

http://jsfiddle.net/x3kYs/3/

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

15 Comments

$('body') is too general and will slow down the page. Should use something more local.
OP does not show and container, so used body, otherwise what you said is correct. Updating it with some container name :)
Most probably you have not removed onblur on your input elements. see my edited answer.
You should add the check also on your form submit so that user will have to correct it before submitting the form. e.g. $('form').submit(function(){return minMaxValues();})
Try parsing the values for integer before comparing. For example try{var val1 = parseInt(inputValue), var2=parseInt(inputValue2); if(val1 < val2) { // do something} else {//do something}}catch(e){return false;}
|
1

This is entirely built upon Nagarjun's answer, but since OP specifically asked for a more reusable solution, consider this...

Change the html thusly:

<div id="container">
    <label for="maxAmount">Maximum Benefit Amount:</label>
    <input name="benefit_max_amount" id="maxAmount" data-range="benefit" data-aspect="max">
    <label for="minAmount">Minimum Benefit Amount</label>
    <input name="benefit_min_amount" id="minAmount" data-range="benefit" data-aspect="min">
</div>

I've added two data attributes to each input. One to group them as a range pair (data-range) and one to distinguish which is which (data-aspect).

Then you can add this javascript and run it anywhere you like, it will only affect pages with elements like those above:

function validate_range() {
    var range = $(this).data("range");
    var min = + $("input[data-range=" + range + "][data-aspect=min]").val();
    var max = + $("input[data-range=" + range + "][data-aspect=max]").val();

    if (min && max && min > max) {
        alert("Invalid Range");
    }
}

$(function () {
    $("#container").on("change", "input[data-range]", validate_range);
});

To reuse the script, you just need to create two inputs and give them a matching data-range and appropriate data-aspects. I leave the task of getting a custom alert message through up to the OP.

Fiddle

2 Comments

Doesn't the very presence of $(function () {}); wrapping a function make it non-modular? That code would have to be on-page, otherwise it would run everywhere, whenever the js is included, on page load. Or, am I missing something?
I'm not sure I know what you mean by "modular". You can have multiple $(document).ready() calls. Is that is what you think is non-modular about it?

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.