Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Javascript validation error

Hi,

I have 2 questions S7 and C1A. The value enter in C1A must be less than or equal to S7. I write the below syntax but it doesn't catch any error. Please let me know why.

 strErrorMessage= "";
var S7value='[%S7_A%]';
var C1value=$("#C1A").val();

//alert("S7value " + S7value);
//alert("C1value " + C1value);


if(C1value>S7value)
{strErrorMessage= "Value must be less than or equal.";}


However this below code works

 if($("#C1A").val()>[%S7_A%])
{strErrorMessage= "Value must be less than or equal.";}


Please let me know
asked Feb 11, 2021 by Abdul Bronze (3,220 points)

1 Answer

+1 vote
The problem with your first posted code is that both variables are going to be strings, S7value because you've surrounded the Sawtooth Script response with apostrophes and C1value because of how jQuery's val function works.  When you compare strings in JavaScript, the result will be whether one field is "greater" from an alphabetic order perspective rather than from a mathematical one.  So this actually returns false:

'12' > '2'


Because the character "1" is considered lower than the character "2" alphabetically.

In your second posted code, the val function will still return a string, but the Sawtooth Script is no longer surrounded by apostrophes so JavaScript treats it like a number.  JavaScript sees that one of these is a number and ends up implicitly converting the other to a number for you.  So this returns true:

'12' > 2


So your second solution works, but it would still be a good practice to get into to make your variables be the type we'd expect them to be.  One option would be to call JavaScript's Number function to convert from a string to a number.  Another option would be to use SSI_GetValue, which returns numbers for numeric fields.

var C1value = Number($("#C1A").val());


var C1value = SSI_GetValue('C1A');
answered Feb 11, 2021 by Zachary Platinum Sawtooth Software, Inc. (201,975 points)
Always a nice reminder to see these little lessons appear on the forum.
...