So I have a function that prompt
s the user for a value (element0
) and compares that value to one already existing (elementIJ.name
). That part works OK, but here comes the problematic twist: I want the function to do something different when the prompt
is cancelled (either by clicking Cancel or pressing the Esc key, for that matter), but instead it looks like the function is terminated. I've been running tests using alert
, but the idea is to actually do other things. Here's my code:
var element0 = prompt('Enter element name').toUpperCase() ;
if ( element0 == null || element0 == '' || element0 == false || !element0 ) { alert('ALERT!') ; }
while ( element0 !== elementIJ.name.toUpperCase() )
{
element0 = prompt('Try again').toUpperCase() ;
if ( element0 === null || element0 === '' || element0 === false ) { alert('ALERT!') ; }
}
// ... do things for element0 === elementIJ.name.toUpperCase()
As I say, the bit without the if
statements works OK, it's just the prompt
cancelling that doesn't. I've been searching the web for answers, but it seems that most people have the exact opposite of my problem: that they want the cancelling to terminate the function... So what am I doing wrong?
Thanks!
You can't do toUpperCase() at the first line because element0 might be cancelled. Try this:
Here is a actually I believe what you were trying to do: Replace 'TEST'
function promptTest(){
var element0 = prompt('Enter element name');
if ( element0 == null || element0 == '' || element0 == false || !element0 ) {
alert('cancelled!')
return false;
}
else{
return element0.toUpperCase();
}
}
var promptVar = promptTest();
while (promptVar && promptVar !== 'TEST' )
{
promptVar = promptTest();
}
var element0 = prompt('Enter element name');
if ( element0 == null || element0 == '' || element0 == false || !element0 ) {
alert('ALERT!') ;
}
else{
element0 = element0.toUpperCase()
console.log("element0: " + element0)
while ( element0 !== elementIJ.name.toUpperCase() )
{
element0 = prompt('Try again').toUpperCase() ;
if ( element0 === null || element0 === '' || element0 === false ) { alert('ALERT!') ; }
}
}