Setting calculated embedded data based on previous answers
Hello, I’m new to JS. I have been trying this for a long time but had no luck. Any advice would be very welcome.
I have a question in a survey asking for employment income. Respondents need to select the way they want to report their salary then enter a numeric value:
I wanted to calculate annual salary based on response to monthly/bi-weekly/hourly rates and show the calculated annual salary to respondents on the next page and confirm it’s the right amount. If it’s not correct, respondents will be able to go back and correct their answer. My JS on the salary question is like this:
And my survey flow is like this:
On the verification page, the calculated field doesn’t show up, and there is no error message either. What went wrong?
Thank you!
Page 1 / 1
Hi,
You don’t need javascript for that, you can use math operations in embedded data fields.
And your embedded data field must be named like that in the survey flow:
__js_CalculatedAnnualSalary
And piped in like that in your validation question:
${e://Field/__js_CalculatedAnnualSalary}
Thank you Vincent. I tried this but see a 0 in the validation page. Did I miss something?
JS in the input question:
My survey flow:
Piped in text:
Validation page:
In @vgayraud’s code, the variables need to be converted to numbers before they are used in the calculation instead of after (i.e., var CalculatedAnnualSalary = parseInt(...). For example:
var Monthly = Number(this.getTextValue(2));
Thank you Tom. The textboxes have been set as numeric values.
I have figured out the issue: the variable index wasn’t 2, 3, or 4
Thanks all!
Actually one last thing to ask, is there a way to add comma separator in the piped variable CalculatedAnnualSalary? Now the number shows like this: