Enforce response of a certain length in textbox

I want participants to enter a uniqueID with length of 6 into a textbox component, and they can only continue to the next part when the text input is exactly length of 6. However, the code I currently have doesn’t seem to enforce the text entry, participants can still press ‘return’ to skip to next section.

In Before Experiement I have the following:

function checkEmpty(text_22) {
  let result;
  if (text_22 == '' || text_22 == ' ') {
    result = 'True';
  } else {
    result = 'False';
  }
  return result;
}

In Each Frame I have the following:

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 === 'return' && text_22.length == 6) {
     textAdd = '';
     continueRoutine = true;
} else if (textAdd === 'space') {
    textAdd = ' ';  // Add a space
} else if (textAdd === 'backspace') {
    text_22.text = text_22.text.slice(0, -1);
    textAdd = undefined;
} else if (['lshift', 'rshift'].includes(textAdd)) {
    modify = true;
} else if (textAdd !== undefined) {
    if (modify) {
        text_22.text = text_22.text + textAdd.toUpperCase();
        modify = false;
    } else {
        text_22.text = text_22.text + textAdd
    }
    textAdd = undefined;
}

Your code ends the routine on return before checking the length.

After changing to the code below, it seems that return key just stopped working. It didn’t end routine even the length was 6

if (textAdd === 'return') {
    textAdd = '';  // Add nothing
    continueRoutine = true;  // End routine (if that is what you want)
} else if (textAdd === 'return' && text_22.length == 6) {
     textAdd = '';
     continueRoutine = false;
}

That’s because your second clause is never checked if the first clause is true.

Try

if (textAdd === 'return' && text_22.length == 6) {
     textAdd = '';
     continueRoutine = false;
}
else if (textAdd === 'return') {
    textAdd = '';  // Add nothing
} 
1 Like

Thanks @wakecarter , your solution worked! One extra thing I had to change was from text_22.length to text_22.text.length

1 Like