You are viewing limited content. For full access, please sign in.

Question

Question

Assistance with JS to validate two fields

asked on January 13, 2021

I am new to Javascript so naturally I am having some issues with inputting the code correctly to get the behavior I want.   I have two fields (Current and Previous MPG). I need for an alert to display if the Current MPG is less than the Previous MPG. With some assistance from a colleague I input this into the JS field. But when I test I do not see the alert displayed.

 

Am I missing something or am I doing this incorrectly?

 

 $('#q671 input').change(function () {
    var x = $('#q671 input').val();
    var y = $('#q672 input').val();


    if (x > y) {
          alert("Current fuel economy must be higher than Previous fuel economy");
          return false;
    }
})


$('#q672 input').change(function () {
    var x = $('#q671 input').val();
    var y = $('#q672 input').val();


    if (x > y) {
          alert("Current fuel economy must be higher than Previous fuel economy");
          return false;
    }
})

0 0

Answer

SELECTED ANSWER
replied on January 13, 2021

Are you sharing just part of your Javascript, or the full thing?

Because if what you posted is the full thing, than you likely just need to wrap it within a document ready statement.

Put this before the beginning:

$(document).ready(function () {

And this after the end:

});

Also, you may want to convert the values to numbers.  The script will often try to do alphabetical comparison instead of numerical comparison and then you get weird things like 15 < 2 evaluating as true.  Here's one way to do it (modifying part of line 2 from your script):

parseFloat($('#q671 input').val());

 

0 0
replied on January 13, 2021

Matthew you are on fire for me today! Thanks alot. I may need to send you a virtual payment for all the help. 

1 0
replied on January 13, 2021

haha - no need @████████- I've got so much help from Laserfiche Answers over the years, it's important to me that I try to pay it forward as much as I can.  Plus challenges like this keep me sharp, and I learn new things too! smiley

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.