Search code examples
javascriptjqueryprompt

cannot get a variable from a prompt as a callback function


On button right click I need:
- hide the button
- then show a prompt
- write the prompt value
- get the value in console

function a_ren(){
	var a = 'lorem';
	$('.cmenu').hide(function(){var res = prompt('RENAME', a);});
	console.log(res);
}

$(document).on('contextmenu', 'button', function(e){
    e.preventDefault();
    a_ren();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='cmenu'>CLICK</button>

Two problems:
- console error - res is not defined
- here on SO the prompt window appears but on my page (chrome, localhost) the prompt window doesn't appear at all.

Any help?


Solution

  • res is undefined because you declare it inside the hide function and try to print it outside of the it(not in the scope). Put the console log inside the function and it should solve it.

    function a_ren(){
    	var a = 'lorem';
    	$('.cmenu').hide(function(){
        var res = prompt('RENAME', a);
        console.log(res);
      });
    }
    
    $(document).on('contextmenu', 'button', function(e){
        e.preventDefault();
        a_ren();
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class='cmenu'>CLICK</button>