oTree Forum >

distBuilder in oTree (or: recording variables from Javascript)

#1 by simoncolumbus (edited )

I would like to use Quentin André's distBuilder Javascript library in oTree to elicit a distribution. I've managed to get it to display right, but I'm struggling to record the output in oTree. The documentation for the library is here: https://quentinandre.github.io/DistributionBuilder/

In my __init__.py file, I have the following:

class Player(BasePlayer):
    my_var = models.StringField()
class MyPage(Page):
    form_model = 'player'
    form_fields = ['my_var']

Then, in the MyVar.html page file, I've included the CSS in a <style> block on top; this works fine (i.e., it displays correctly). The distributionsbuilder.min.js file is in the 'static' folder. However, I am struggling with recording the output of the distributionbuilder into my 'my_var' StringField. The full Javascript code to be included in the MyVar.html is below. The crucial bit is this:

    $j("#SubmitDistribution").click(function() {
        var my_var = distbuilder.getDistribution().join;
        <-- record data here -->
I first join everything into a string; then, I somehow need to push this to oTree---that's where I'm stuck. I'd much appreciate any suggestions!

Full code for MyVar.html:

    {{ formfield_errors 'my_var' }}
    <div id="targetdiv"></div>

    <script src="{{ static 'distributionbuilder.min.js' }}"></script>

    var distbuilder = new DistributionBuilder({
        nRows: 5,
        nBuckets: 11,
        minVal: 0,
        maxVal: 10,
        nBalls: 5,
        onTouch: function () {
            console.log("Distbuilder was touched!")
        onChange: function () {
            console.log("Distbuilder was updated!")
            if (this.isComplete()) {
                $j("#SubmitDistribution").attr("disabled", false)
            } else {
                $j("#SubmitDistribution").attr("disabled", true)
            toggleGridClick: true,
            addTotals: true
    $j("#SubmitDistribution").click(function() {
        var my_var = distbuilder.getDistribution().join;
        <-- record data here -->
        labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#2 by Chris_oTree

Either use liveSend or write it to a hidden form field.

Write a reply

Set forum username