psychopy.org | Reference | Downloads | Github

Code component for typing response

Hi, everyone!
I am struggling with translating python code to JS.
In my experiment, participants have to solve anagrams and type the answers. The experiment is made in Builder, and I have a code component that allows participants to type their answers. Here it is:

# Begin routine
corr = 0
import pyglet
from pyglet.window import key

mytext='';
def on_text(text):
    global mytext
    mytext=mytext+text
def on_key_press(symbol,modifiers):
    global continueRoutine,mytext
    if symbol == key.ENTER:
        exp.addData('answer',mytext)
        exp.addData('answer.rt',trialClock.getTime())
        if mytext == corans:
            corr = 1
        else:
            corr = 0
        exp.addData('answer.corr',corr)
        continueRoutine=False
    elif symbol == key.BACKSPACE:
        mytext=mytext[:-1]

wins = pyglet.window.get_platform().get_default_display().get_windows()

for window in wins: 
    window.push_handlers(on_text,on_key_press)

# End routine
for window in wins: 
    window.pop_handlers()

As I know, code components have to be translated to JS manually in order to make them work. Unfortunately, I have zero experience in JS, but I made an attempt:

var mytext=''
function on_text(text){
    mytext=mytext+text;
}

function on_key_press(symbol,modifiers) {
    if (enter>0){
        exp.addData('answer',mytext)
        exp.addData('answer.rt',trialClock.getTime())
        continueRoutine=false;
   }    else if (backspace>0){
            mytext=mytext[:-1];
   }
}

Surely, it doesn’t work. So, I have two questions:

  1. Is there a convenient way to write a JS code doing similar things?
  2. Could anyone help me rewrite the python code above in JS?
    Thanks!

Hi there,

If you search on Pavlovia there is a demo called textInput that includes a JS code component which allows participants to type their answers.

Jenny

@jretz Thank you for the answer! I used the code from the demo you mentioned.

1 Like