Search code examples
javascriptmodal-dialogalertsweetalertsweetalert2

How to store user input as a variable with a modal dialog library? (JavaScript)


I'm trying to save user input via alert as a variable. I actually can do it via JS using prompt, but can't implement a similar solution with sweetalert and sweetalert2 libraries.

I read through their documentation and examples:

https://sweetalert.js.org/guides/#advanced-examples
https://sweetalert2.github.io/#input-types

My efforts return [Object promise] placeholder instead of variable text in the best case, but usually, it is not working at all: https://codepen.io/dimos082/pen/xeXmqK

Here's the implementation that works for me in JavaScript with alert pop-ups: https://codepen.io/dimos082/pen/ROLEpo

<html>
<body>
    <button onclick="TellTale()">Tell me a story</button>
    <p id="Tale"></p>  <!-- Result from TellTale() will be put here as innerHTML-->  
</body>
<script> 
    function TellTale() {let KnightName = prompt("How do people call you, oh Noble Knight?");
    document.getElementById("Tale").innerHTML = "Once upon a time, there lived a champion, noble Sir " + KnightName + "."}
</script>
</html>

I look for the same variable handling as in the code above. Is it possible with those 2 libraries, or you can suggest a better solution for replacing standard alerts?

Thank you!


Solution

  • Solution to this problem:

    <head>
        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
        </head>
    <html>
    <body>
        <button onclick="TellTale()">Tell me a story</button>
        <p id="Tale"></p>  <!-- Result from TellTale() will be put here as innerHTML-->  
    </body>
    <script> 
    function TellTale() {
     swal("How do people call you, oh Noble Knight?", {
       content: "input"
     }).then(KnightName => document.getElementById("Tale").innerHTML = "Once upon a time, there lived a champion, noble Sir " + KnightName + ".")
    }
    </script>
    </html>