#1 by Yamani
Hello, I'm a beginner in otree. I've some issue that make me feel bad. I have a question with several questions. One of the questions asks whether the respondent has an account or not, and if he answers yes, we then ask him who holds this account (himself, a relative, his employer...) and if not, we skip the question. The problem is that I can't implement a code in Otree Studio that allows me to do this. I need your help, please.
#2 by BonnEconLab
If you put the follow-up question on a separate page, you can use oTree’s is_displayed function to display that page only if the “account” question has been answered “yes”. See https://otree.readthedocs.io/en/latest/pages.html#is-displayed.
#3 by Yamani
Thank you very much for your help. I did notice this in the functions that Otree offers, however what I am being asked to do is to make it so that everything happens on the same page, without switching to another. Is there a way to do this on Otree?
#4 by BonnEconLab
On the same page, you can use JavaScript to hide/unhide elements. Let’s assume that your first player field is called “account” and the second player field is called “account_owner”. Let’s also assume that the first “account” questions has options “yes” and “no” (in that order). Then including the following JavaScript code at the end of the HTML file should work: <script> // Hide the "account_owner" question by default document.getElementById("id_account_owner").style.display = "none"; document.querySelector("[for='id_account_owner']").style.display = "none"; function toggleAccountOwner(r) { if (r == 0) { // Show "account_owner" question if first "account" radio button is selected document.getElementById("id_account_owner").style.display = "block"; document.querySelector("[for='id_account_owner']").style.display = "block"; //document.getElementById("id_account_owner").value = ""; // if the "account_owner" input field were type="text" } else { // Hide "account_owner" question otherwise document.getElementById("id_account_owner").style.display = "none"; document.querySelector("[for='id_account_owner']").style.display = "none"; //document.getElementById("id_account_owner").value = "N/A"; // if the "account_owner" input field were type="text" }; }; // After page has finished loading, assign toggleAccountOwner function to "account" radio buttons window.addEventListener("load", function(){ var accountRadios = document.getElementsByName("account"); for (let r = 0; r < accountRadios.length; r++) { accountRadios[r].oninput = function() { toggleAccountOwner(r); }; }; }); </script> Make sure in oTree that the “account_owner” player field is allowed to remain empty. (Alternatively, it is straightforward to extend the above JavaScript code so that it sets the “account_owner” input field to a value like “not applicable”/“not assigned”.)
#5 by Yamani
Thank you for your help, thanks :)
#6 by Yamani
Thank you for your help, thanks :)
#7 by Yamani
Thank you for your help, thanks :)