#1 by Roger97
Hey there! I would need some help on how to make a formfield visible on a page only after the user has completed some other previous formfields. In my case, for example, I need a text box of motivation to pop up in the same page only after the user has completed a decision task.
#2
by
BonnEconLab
This can be achieved via JavaScript. Here’s a minimal working example. It assumes that you have only two form fields, “task” and “motivation”. ====================================================================== Contents of the __init__.py file: ====================================================================== from otree.api import * doc = """ Unhide a form field depending on input in another form field, using JavaScript. """ class C(BaseConstants): NAME_IN_URL = 'zzz_show_formfield' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): task = models.BooleanField() motivation = models.LongStringField() # PAGES class MyPage(Page): form_model = "player" form_fields = ["task", "motivation"] page_sequence = [ MyPage, ] ====================================================================== Contents of MyPage.html: ====================================================================== {{ block title }} Task, followed by text input {{ endblock }} {{ block content }} {{ formfield "task" }} {{ formfield_errors "task" }} <div id="motivation-input" style="visibility: hidden;"> {{ formfield "motivation" }} {{ formfield_errors "motivation" }} </div> <div id="next-button" style="visibility: hidden;"> {{ next_button }} </div> {{ endblock }} {{ block scripts }} <script> function showMotivationInput() { document.getElementById("motivation-input").style.visibility = "visible"; }; function showNextButton() { motivationInput = document.getElementById("id_motivation").value; if (motivationInput.length > 0) { document.getElementById("next-button").style.visibility = "visible"; } else { document.getElementById("next-button").style.visibility = "hidden"; }; }; document.getElementById("id_task-0").oninput = function() { showMotivationInput(); }; document.getElementById("id_task-1").oninput = function() { showMotivationInput(); }; document.getElementById("id_motivation").oninput = function() { showNextButton(); }; </script> {{ endblock }} ====================================================================== (The JavaScript code relies on the rest of the page being loaded when the script is executed. Placing the JavaScript code at the end should ensure that the rest of the page is loaded first, before the JavaScript is executed.) Your JavaScript code will depend, of course, on the specifics of your decision task.
#3 by Roger97
thanks a lot!