Constrain Keyboard responses to numbers

URL of experiment: https://run.pavlovia.org/arkadiym/pic_rate_a_1/html

Description of the problem: My experiment contains a routine in which participants enter a responses on the screen. I was wondering if someone might know how I can constrain participants’ responses to just numbers, so that random keys are not inputted as part of the responses. Below is the code:

In Builder, entered into each frame, on the python (left) side:

keys = event.getKeys()
if len(keys):
    if 'space' in keys:
        text.text = text.text + ' '
    elif 'backspace' in keys:
        text.text = text.text[:-1]
    elif 'lshift' in keys or 'rshift' in keys:
        modify = True
    elif 'return' in keys:
        continueRoutine = False
    else:
        if modify:
            text.text = text.text + keys[0].upper()
            modify = False
        else:
            text.text = text.text + keys[0]

In Builder, entered into each frame, on the javascript (right) side:

let theseKeys = psychoJS.eventManager.getKeys();
if (theseKeys.length > 0) {  // at least one key was pressed
  textAdd = theseKeys[theseKeys.length-1]; 
  }


if (textAdd === 'return') {
    textAdd = '';  // Add nothing
    continueRoutine = false;  // End routine (if that is what you want)
} else if (textAdd === 'space') {
    textAdd = ' ';  // Add a space
} else if (textAdd === 'backspace') {
    text.text = text.text.slice(0, -1);
    textAdd = undefined;
} else if (['lshift', 'rshift'].includes(textAdd)) {
    modify = true;
} else if (textAdd !== undefined) {
    if (modify) {
        text.text = text.text + textAdd.toUpperCase();
        modify = false;
    } else {
        text.text = text.text + textAdd
    }
    textAdd = undefined;
}

Keyboard components have a paramater ‘allowed keys’ which you could set to ‘1’,‘2’,‘3’,‘4’…

You do need quotes and commas - these are the names of the keys not the numbers they represent.

1 Like