Search code examples
javascriptphpprompt

Javascript return prompt onclick


I want to check for empty prompt and null both in same command.

These 2 work on its own:

  • first checks for empty string (although maybe not tab necessarily?)

  • second checks for null (cancel)

I dont know how to combine them in single line?

<a href="#" onclick="return prompt('Enter title for new player:') != ''">Duplicate</a>

<a href="#" onclick="return prompt('Enter title for new player:') != null">Duplicate</a>

EDIT: (my example is little more complicated)

I use php for translation:

<a href="#" class="btn" onclick="return prompt('<?php printf(esc_attr__('Enter title for new player:', 'domain'))?>') || false"<?php _e('Duplicate', 'domain'); ?></a>

I need to get title of successful prompt (so I can send it with GET)

I tried:

$('.btn').on('click', function(){
    var btn = $(this), val = btn.val();

    if(val !== null || val != ''){
        console.log(val)
    }
});

but it returns empty string always.


Solution

  • If you wish to continue only when you have an input supplied, and re-prompt if no value supplied, then call the prompt again depending on the result.

    <a href="#" onclick="getName()">Enter title</a>
    
    <script>
        function getName() {
            var name = prompt('Enter name for new player:');
    
            if(name == null || name == "") {
                getName();
            }
    
            return name;
        }
    </script>