oTree Forum >

I want to players to allocate percentages of their endowment over 5 options. How can this be done on otree?

#1 by sthom (edited )

I want that the total allocations over the 5 options should sum to 100

#2 by BonnEconLab (edited )

What you intend to do is the very example provided on on https://otree.readthedocs.io/en/latest/forms.html?highlight=error_message#validating-multiple-fields-together.

To provide real-time feedback to participants, I would suggest, however, to do the validation via JavaScript. Here is a self-contained HTML file including the respective JavaScript. The JavaScript code calculates the sum of the values entered into the five input fields. It displays this sum in green if it equals 100 and in gray if it does not equal 100. It also displays a (nonfunctional) “Next” button if the sum equals 100 and hides the button if that is not the case:



<title>Five questions, answer needs to sum to 100</title>



<h1>Please input five values</h1>
<p>The sum of the inputs must equal 100.</p>
        <td>Input no.&nbsp;1:</td>
        <td><input id="input-1" type="number" min="0" max="100" /></td>
        <td>Input no.&nbsp;2:</td>
        <td><input id="input-2" type="number" min="0" max="100" /></td>
        <td>Input no.&nbsp;3:</td>
        <td><input id="input-3" type="number" min="0" max="100" /></td>
        <td>Input no.&nbsp;4:</td>
        <td><input id="input-4" type="number" min="0" max="100" /></td>
        <td>Input no.&nbsp;5:</td>
        <td><input id="input-5" type="number" min="0" max="100" /></td>
        <td style="color: gray">Sum of all inputs:</td>
        <td style="color: gray"><span id="summed-inputs">0</span></td>

<p id="next-button"><button id="next_button">Next</button></p>

    var inputs = document.getElementsByTagName('input');
    var amounts = Array(inputs.length).fill(0);
    function calculateSum() {
        var sum = 0;
        for (i = 1; i <= inputs.length; i++) {
            amounts[i] = parseInt(document.getElementById('input-' + i).value) || 0;
            sum = sum + amounts[i];
        document.getElementById('summed-inputs').innerHTML = sum;
        if (sum == 100) {
          document.getElementById('summed-inputs').style.color = "green";
          document.getElementById('next-button').style.visibility = "visible";
        } else {
          document.getElementById('summed-inputs').style.color = "gray";
          document.getElementById('next-button').style.visibility = "hidden";
    for (i = 1; i <= inputs.length; i++) {
        document.getElementById('input-' + i).oninput = function() { calculateSum(); };



Write a reply

Set forum username