Have an idea?

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

Remaining constant sum baked right into the question (visually)

In follow-up to this, I also need a constant sum "remaining" field below the total field. Is there a way to do this as well?

I know this is totally not the code, but something akin to this (I'm guessing):

<script type="text/javascript">
$(document).ready(function(){
    $('#q22_div 
    <tr>
        <td class="input_cell"><input name="q22_remaining" type="text" size="3" class="total text_input" id="q22_remaining"></td>
        <td class="option_cell"><div class="options">Remaining</div>
        </td>
    </tr>
</script> 
related to an answer for: Constant Sum error message math
asked Apr 14, 2016 by WTW_cal Bronze (1,145 points)

1 Answer

+1 vote
 
Best answer
That's not a bad start.  To insert the new "<tr>", we need to use a jQuery function called "after."  You can see how I use this in line 4: the first part gets us to the location of what is currently the last "<tr>" and then I give it some more HTML to add after that location.

If you are interested in learning more jQuery, I would recommend http://www.w3schools.com/.  They have free courses in jQuery and many other languages that can be used in web programming.

<script type="text/javascript">
$(document).ready(function(){
    // Add "Remaining" field
    $('#ConstantSumQ_div .question_body table table tbody > tr:last-child').after('<tr><td><input id="ConstantSumQ_remaining" class="total text_input" size="3"></td><td>Remaining</td></tr>');
    $('#ConstantSumQ_remaining').prop('disabled', true);
    $('#ConstantSumQ_remaining').css('color', 'black');
    $('#ConstantSumQ_remaining').val(100);
    
    // Update "Remaining" field
    var inputs = $('#ConstantSumQ_div .question_body input').length - 3;
    $('#ConstantSumQ_div .question_body input').keyup(function(){
        var sum = 0;
        for (var i = 1; i <= inputs; i++)
        {
            var field = $('#ConstantSumQ_' + i).val();
            sum += parseInt(field) || 0;
        }
        $('#ConstantSumQ_remaining').val(100 - sum);
    });
})
</script>


Per the usual, you can replace "ConstantSumQ" and "100" with your question name and total.
answered Apr 14, 2016 by Zachary Platinum Sawtooth Software, Inc. (67,750 points)
selected Apr 15, 2016 by WTW_cal
...