Search code examples
javascriptescapingkeykeycode

How to prevent abort by pressing ESC key (Javascript)?


I would like to prompt a string. My additional need is to not escape by pressing the ENTER or ESC key. With this method ENTER works (doesn't escape):

var f1 = '';
while (f1.length < 1) {
  f1 = prompt('Please give a value of the string!');
}

How can I reach, that this script doesn't escape by pressing ESC either? Thanks, hazazs


Solution

  • prompt returns null when you click ESC button. You need to check null also in while

    while (f1 == null || f1.length < 1)
    

    Or simply

    while (!f1)
    

    Use this one:

    var f1 = '';
    while (!f1) {
         f1 = prompt('Please give a value of the string!');
    }
    

    Note: As Cancel and ESC both returns null, you will not be able to Cancel it though.