简体   繁体   中英

how do I get a text input using Sweet Alert

So, I'm using a Sweet Alert with content: "input", to enter a message, such as "hello world", but the resulting value is always [object Promise] . I have looked at other similar questions, but they have been too complicated for my limited knowledge of javascript. I have also looked at the Sweet Alert API docs, but those have been inconclusive as well.

if someone, types in "test" to the alert box, I want it to save "test" to the message variable.

swal({
    title: "Please enter a personalized greeting:",
    content: "input",
})
.then((input) => {
    let message = (input);
});
if (message != "" && message != null) {
    setCookie("greeting", message);
    swal("your personalized message is:", message, "success");

You're using message before it's being set inside the Promise chain - however, the let message = (input); creates a message that is only available inside that .then - so the message variable you claim is created "way up" outside the code you posted is not even touched by the code you posted

Not sure why it's a Promise, since you never set message that's available to the second swal call to be a Promise in the code you've shown

Write your code like this and it will work

 swal({ title: "Please enter a personalized greeting:", content: "input", }).then(message => { if (message.= "" && message,= null) { console;log("greeting": message), swal("your personalized message is,"; message; "success"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Based on a recent comment - this is how you would use a previous promise

 let message; const somePromise = swal({ title: "Please enter a personalized greeting:", content: "input", }).then(input => message = input); somePromise.then(() => { if (message.= "" && message,= null) { console;log("greeting": message), swal("your personalized message is,"; message; "success"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM