psychopy.org | Reference | Downloads | Github

Restricting certain keys in text input

Hello,

I have a task where the participant is required to type a response to a question.

To allow text input, I have copied the code from a recommended text input experiment ( https://gitlab.pavlovia.org/demos/textinput/ . The JS code is as follows:

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 === 'period') {
    textAdd = '.';  // Add a period
} 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;
}

If I understand correctly, the .getKeys() command summons all available keys on the keyboard. Pressing the period button prints the word “period”, but I have corrected this using: } else if (textAdd === 'period') { textAdd = '.'; // Add a period

However, keys such as “num_1”, “backslash”, “equals”, etc are also being printed when I don’t really need them. I only need the alphabet, the numbers (not numpad) and some punctuation. Would I need to replicate the same process for every other key or is there a way I can restrict these keys from being pressed/registered?

Thanks in advance.

Hi @Nicholas_Borg , the getKeys method takes a keyList argument, allowing you to define which keys should be checked for. E.g., use:

let theseKeys = psychoJS.eventManager.getKeys({keyList: ['a', 'b', 'c']})
// This example will only accept keys 'a', 'b', and 'c'
1 Like

Thank you @dvbridges, that worked perfectly. Will check out the documentation a bit better next time :slight_smile: