jeudi 3 janvier 2019

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

Aucun commentaire:

Enregistrer un commentaire