Search code examples
jqueryconfirm

force user to populate confirm dialog


I want to force user to enter image name inside prompt dialog.

If he clicks CANCEL - the dialog should appear again.

Also the name must have at least 3 letters.

The below code works only if a user clicks CANCEL once. Second time - it is closed.

It should appear again and again - untill 3-letters name is there.

Any idea?

$('button').on('click', function(){
    var name = prompt('IMG NAME', '');
    if(name == null){name = prompt('IMG NAME', '');}
    if(name.trim() == "" || name.length < 3){var name = prompt('IMG NAME', '');}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>CLICK</button>


Solution

  • Just use a loop:

    $('button').on('click', function(){
        var name;
        while(!name || name.trim().length < 3) {
            name = prompt('IMG NAME', '');
        }
        $(this).text("You entered: " + name.trim());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <button>CLICK</button>