Search code examples
javascripthtmlif-statementsweetalert2

Swal.fire when click text in Javascript (Sweetalert)


I want to make appear a window promp with sweetalert (swal.fire) when i click a text. How do if statements and window prompt work on this library? After this point, you can appreciate that i'm new in this programming world.

After that, i would like to asign a value to that input and verify if the answer is correct or not.

<td class="gases" title="Hidrógeno" id="H">H</td> This is the element i want to click

Swal.fire({
title:'¿Cuál es el elemento?',
text: 'Introduce el nombre aquí',
input: 'text',
inputPlaceholder: 'Nombre', })

This is the prompt i want to appear when i cliked that element. When the button 'OK' is clicked, want to verify if the name introduced is correct or not...:

if (name === hidrógeno) {
     Swal.fire ('Correct!', 'You got the answer right!', 'success') }

else {
     Swal.fire ('Incorrect...', 'You failed!', 'error') }

Solution

  • First attach a click event listener to your text that you want to be clickable. You can do this by grabbing your element using querySelector() and its class name, and then adding a click event handler to it with .addEventListener():

    const elem = document.querySelector(".gases");
    
    elem.addEventListener("click", () => {
      // callback function
    });
    

    Inside of the callback function to addEventListener, you can open your sweetalert question popup using Swal.fire(). This method returns a promise, which resolves to the text entered by the user. To grab the resolved value from this promise, you can attach a .then() and destructure the entered text from the arguments:

    const elem = document.querySelector(".gases");
    elem.addEventListener("click", () => {
      Swal.fire({
        title: '¿Cuál es el elemento?',
        text: 'Introduce el nombre aquí',
        input: 'text',
        inputPlaceholder: 'Nombre',
      }).then(({value}) => {
        if (value === "hidrógeno") {
          Swal.fire('Correct!', 'You got the answer right!', 'success')
        } else {
          Swal.fire('Incorrect...', 'You failed!', 'error')
        }
      });
    });
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
    
    <table>
      <tr>
        <td class="gases" title="Hidrógeno" id="H">Click</td>
      </tr>
    </table>