Have an idea?

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

Issue with JavaScript validation

I have a numeric question with Don't know and prefer not to answer options. So I used free format to program this question. I made all the 3 options as not required and had the below validation.
It has no problem except until I enter zero. If I enter zero it throws error 'A Response is required.' (first logic). If I enter zero along with Don't know option checked, it doesn't throw any error and goes to next page.


 
var strErrorMessage="";

var numBox = SSI_GetValue("[% QuestionName() %]_N");

if(SSI_GetValue("Q2C_C1_1")=="" && SSI_GetValue("Q2C_C2_1")=="" && numBox == "")
{strErrorMessage = "A Response is required.";}
else if((SSI_GetValue("Q2C_C1_1")!="" && (SSI_GetValue("Q2C_C2_1")!="" || numBox != "")) || (SSI_GetValue("Q2C_C2_1")!="" && numBox != ""))
{strErrorMessage = "Please provide only one answer.";} 




I solved this issue by the below script, but I would like to know what is wierd happening at above numBox variable. It could be my learning, please let me know.



 
var strErrorMessage="";

var min=document.getElementById("[% QuestionName() %]_N");

if(SSI_GetValue("Q2C_C1_1")=="" && SSI_GetValue("Q2C_C2_1")=="" && min.value.length < 1)
{strErrorMessage = "A Response is required.";}
else if((SSI_GetValue("Q2C_C1_1")!="" && (SSI_GetValue("Q2C_C2_1")!="" || min.value.length > 0)) || (SSI_GetValue("Q2C_C2_1")!="" && min.value.length > 0))
{strErrorMessage = "Please provide only one answer.";} 



My numeric input box


<input name="[% QuestionName() %]_N" id="[% QuestionName() %]_N" class="numeric_input" type="tel" size="5"> 
asked Aug 27, 2019 by Abdul Bronze (2,630 points)

2 Answers

0 votes
I didn't fully test the code, but I'm guessing it's the use of '==' which will test 0=="" as 'true'.

A triple equals '===' will test 0==="" as 'false'.

Double equals does type conversion (e.g. string to number) where as triple equals requires matching on both type and value.
answered Aug 27, 2019 by Kenneth Fairchild Bronze Sawtooth Software, Inc. (3,820 points)
0 votes
What Kenneth said is correct.  If it's not already clear, I would also clarify that when SSI_GetValue is called on a numeric variable with a non-numeric response (e.g., an empty response), it returns the number 0 rather than the empty string.  So if you ever need to distinguish between a respondent actually typing in the number 0 and not typing in anything at all, you will want to use existing JavaScript / jQuery methods to get the contents of the textbox, instead of calling SSI_GetValue.
answered Aug 27, 2019 by Zachary Platinum Sawtooth Software, Inc. (147,925 points)
...