Search code examples
jquerysweetalert2

Sweetalert 2 textarea async


I tried with this simple example of documentation https://sweetalert2.github.io/ but i get the error message :

Uncaught SyntaxError: await is only valid in async function

$(document).ready(function() {
  $('.buttonproblem').click(function() {
    const { value : text } = await swal({
      input: 'textarea',
      inputPlaceholder: 'Type your message here',
      showCancelButton: true
    })

    if (text) {
      swal(text)
    }
  })   
});

Solution

  • The issue is because you need to declare the click handler function as async in order to use the await keyword within it. Try this:

    $('.buttonproblem').click(async function() { // note use of 'async' here
      const text = await swal({
        title: 'foo', // Note this was missing in your example
        input: 'textarea',
        inputPlaceholder: 'Type your message here',
        showCancelButton: true
      })
    
      if (text) {
        swal(text)
      }
    })
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
    
    <button class="buttonproblem">Click me</button>

    Note that your const { value: text } syntax was causing an error, although the logic worked fine, so I removed it.