Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Sweet Alert inside a If Statement

I'am trying (without luck) to implement a Swal inside a If statement.

here is what i've done:

function myFunction() {
    /* Get the text field */
    var copyText = document.getElementById("numero");
    
    //check if try to copy with the empty input 
    if(document.getElementById("numero").value == ""){
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: 'Nothing to copy!'        
          })      
        // alert("Nothing to copy!!")
    } else {
    
    }

And here is the links in my html:

  <!-- dark theme for swal -->
    <link href="//cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet"> 
    
    <!-- javascript file  -->
    <script src="app.js"></script>
    
    <!-- swal link -->
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Any tip to how can I make this work? I guess my problem is inside the If statement, but I don't know how to fix it

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In your code, I am not seeing an event listener. Use keyup to verify that the value of the elemnt is empty.

var copyText = document.getElementById("numero");

copyText.addEventListener('keyup', () => {
  if (document.getElementById("numero").value == "") {
    Swal.fire({
      icon: 'error',
      title: 'Oops...',
      text: 'Nothing to copy!'
    })
  }
})
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>

    <head>
      <link href="//cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
      <script src="app.js"></script>
      <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    </head>
  </head>

  <body>
    <input type="text" id="numero">
  </body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

end up that everything was working nice, but... I forget to put this in my code

event.preventDefault()

That prevent the Swal to not work well.

By the end, the final code went like this:

function myFunction() {
    /* Get the text field */
    var copyText = document.getElementById("numero");
 
    if(document.getElementById("numero").value == ""){

        Swal.fire(
            'Ooops...',
            'Nothing to copy here!',
            'error'          
          )
          event.preventDefault()
 
    } else {}
    /*code here
    }

Thanks for giving me that tips guys 😉

about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, make sure your imports are correct. You can try debugging by using something simple like: swal("Hello world") anywhere in your code. I roughly copied yours and used a different CDN import from the Swal documentation on their website: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

In your Javascript code, you're missing a } at the end of your function. Might also be a miscopy, but never too sure.

Also, if you want to make sure your if statement is correct, you can try debugging with console.log("Hello world") at every fork in your code. Then, open the console in your browser to see what is logged. This will help you figure out whether or not your code is running when you want it to.

Also, watch out when you use document.getElementById("numero").value. For instance, your code wouldn't work with <p> because <p> has no value, but it would with <input> or <option>.

Here is a sample of code that is working on my end:

function myFunction() {
    var copyText = document.getElementById("numero");

    if (document.getElementById("numero").innerHTML == "") {
        swal({
            icon: 'error',
            title: 'Oops...',
            text: 'Nothing to copy!'        
        })     
    } else {
        swal("Copied!")     
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda