Have an idea?

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

Using SetValue to change a previous response


My requirement is to change the response value of a previous question based on certain condition which is evaluated later on.

The complete code is as below:

var children = 0;
var childCount = 0;

if ([% Answered(D5_r2_c1) %]) {
    children = parseInt([% D5_r2_c1 %]);

var childUnder6 = parseInt([% S6_1 %]);
var child6To12 = parseInt([% S6_2 %]);
var child13To18 = parseInt([% S6_3 %]);
var childAbove18 = parseInt[% S6_4 %]);

var childCount = childUnder6 + child6To12 + child13To18 + childAbove18;

if (childCount && (children === 0)) {
    [% SetValue(S6_5, 1) %];
    [% SetValue(S6_1, 0) %];
    [% SetValue(S6_2, 0) %];
    [% SetValue(S6_3, 0) %];
    [% SetValue(S6_4, 0) %];

I have put the above code in the advanced JavaScript verification space of D6 question which occurs after both the questions S6 and D5. What I am currently facing is that the database changes as soon as the D6 page loads, even when the 'if' condition used is false based on the responses.

I have below questions:

1. Is this the expected behavior of the code, because according to the advanced verification help, this code should execute only after the submit button is clicked on the page?
2. Irrespective of the timing of the code execution, why are my responses changing even when the condition is false?
3. What changes should I make to achieve my requirement?

Thanks in advance for your response.
asked Sep 27, 2018 by prashant (180 points)

1 Answer

+1 vote
One of the things you have to keep in mind while writing code for a questionnaire is that JavaScript is client-based, while Sawtooth Script is server-based.  That's why you can't put Sawtooth Script into a JavaScript if block - because all Sawtooth Script is ran before any JavaScript runs.

The workaround is to move the entire code into unverified Perl and to locate that code on a page after D5 and S6.  Here's my quick attempt at rewriting your code in Perl:

[% Begin Unverified Perl
my $children = 0;
my $childCount = 0;

if (ANSWERED('D5_r2_c1')) {
    $children = GETVALUE('D5_r2_c1');

$childCount += GETVALUE('S6_1');
$childCount += GETVALUE('S6_2');
$childCount += GETVALUE('S6_3');
$childCount += GETVALUE('S6_4');

if ($childCount && $children == 0) {
    SETVALUE('S6_5', 1);
    SETVALUE('S6_1', 0);
    SETVALUE('S6_2', 0);
    SETVALUE('S6_3', 0);
    SETVALUE('S6_4', 0);
End Unverified %]
answered Sep 27, 2018 by Zachary Platinum Sawtooth Software, Inc. (212,650 points)