Search code examples
javascriptvariablesif-statementprompt

Recursive prompt function returns null


I want to build a prompt function that will prompt until user inputs a value and then return that value.

Why this code returns null when I enter in mandatory mode and then enter a value? Can anyone make it working?

function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';
  if (typeof mandantory === 'undefined')
    return prompt(text, defaultText);
  else {
    var a = prompt(text, defaultText);
    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else {
      return null;   
    }
  }
}
<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
		<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
	</body>
</html>

Note: it has to be called from onclick="...".

Thanks, Dejan


Solution

  • It's returning null because you are returning it in your else if a value is entered. In your last else you need to return a instead of null, when a is different from '':

    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else {
      return a;   
    }
    

    Note:

    To check if a variable is defined, you can just use if(mandatory) instead of writing if(typeof mandantory === 'undefined').

    Demo:

    function UserInput(text, defaultText, mandantory) {
      if (typeof defaultText === 'undefined')
        defaultText = '';
      if (mandantory)
        return prompt(text, defaultText);
      else {
        var a = prompt(text, defaultText);
        if (a === '') {
          return UserInput(text, defaultText, mandantory);
        } else {
          return a;   
        }
      }
    }
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>Page Title</title>
    	</head>
    	<body>
    		<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
    		<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
    	</body>
    </html>