Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  18] [ 3]  / answers: 1 / hits: 25221  / 3 Years ago, sun, may 30, 2021, 12:00:00

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') }

More From » html

 Answers
11

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/[email protected]/dist/sweetalert2.all.min.js></script>

<table>
<tr>
<td class=gases title=Hidrógeno id=H>Click</td>
</tr>
</table>




[#50275] Friday, April 30, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelynn

Total Points: 378
Total Questions: 86
Total Answers: 108

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
katelynn questions
Fri, Mar 12, 21, 00:00, 3 Years ago
Mon, Nov 16, 20, 00:00, 4 Years ago
Thu, Jul 23, 20, 00:00, 4 Years ago
Wed, Apr 15, 20, 00:00, 4 Years ago
;