Using SweetAlert and jQuery to enhance form inputs

I'm facing an issue with my form that has two states. The first state requires inputs to be filled, while the second state requires them to be empty. I'm using Sweet Alert to display the input result, but for some reason, my if-else statement is not working correctly. Here's my form code:

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.5.0/sweet-alert.css"/>
       <form method='post'>
            <input type="text" name="nombre" id="nombre" autofocus required placeholder="Escribe tu nombre (Obligatorio)"/>
            <br>
            <input type="mail" name="mail" id ="mail" required placeholder="Escribe tu correo (Obligatorio)">
            <br>
            <input type="tel" name="telefono" placeholder="Escribe tu teléfono" />
            <br>
            <textarea rows="5" cols="35" name="mensaje" id="mensaje" required placeholder="Escribe tu mensaje (Obligatorio)"  /></textarea>
            <br>
            <input type="submit" id="enviar" value="Enviar" />
        </form>

Below is my jQuery code snippet:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.5.0/sweet-alert.min.js"></script>

$("#enviar").click(function () {
    if ($("#nombre").is(':empty')){
        swal({
            title: "Datos incorrectos.",
            text: "No se ha enviado el correo.",
            type: "warning", 
            allowOutsideClick: false,
            timer:5000,
        });
    }

    if ($("#nombre").not(':empty')){
        swal({
            title: "Correcto.",
            text: "Se ha enviado el correo.",
            type: "success", 
            allowOutsideClick: false,
            timer:5000,

        });
    }
});

Can anyone provide any insights or suggestions on how to fix this issue?

Answer №1

$(function() {
  $("#enviar").click(function (event) {
      
      if ($("#nombre").val()) {
        swal({
          title: "Correcto.",
          text: "Se ha enviado el correo.",
          type: "success", 
          allowOutsideClick: false,
         timer:5000,
        });
      }
      else {
        swal({
          title: "Datos incorrectos.",
          text: "No se ha enviado el correo.",
          type: "warning", 
          allowOutsideClick: false,
          timer:5000,
        });
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.5.0/sweet-alert.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.5.0/sweet-alert.css"/>
       <form method='post'>
            <input type="text" name="nombre" id="nombre" autofocus required placeholder="Escribe tu nombre (Obligatorio)"/>
            <br>
            <input type="mail" name="mail" id ="mail" required placeholder="Escribe tu correo (Obligatorio)">
            <br>
            <input type="tel" name="telefono" placeholder="Escribe tu teléfono" />
            <br>
            <textarea rows="5" cols="35" name="mensaje" id="mensaje" required placeholder="Escribe tu mensaje (Obligatorio)"  /></textarea>
            <br>
            <input type="submit" id="enviar" value="Enviar" />
        </form>

I utilized $("#element").val(), a function that returns true if the 'val' is not empty and false if it is empty.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update a row in an angular table when a table cell contains multiple items

I am currently using angular.js to display a table. In my table, each spot contains two important pieces of information which are the data and the color. While I have managed to find solutions for editing the data, I am seeking suggestions on how to change ...

Add a class to a particular element within an ngFor loop

I wrote a loop that creates names along with icons. My goal is to make the icon appear only when it is hovered over. <div class="elm" *ngFor="let element of callWorkflowData?.jobsList"> <mat-card (mouseover)="hover=true" (mouseleave)="hover= ...

Unlocking the JSON array of data in JavaScript: A step-by-step guide

Hey there, I need help extracting an array from a JSON data structure. Here's an example of my JSON object: { Data1 : { Data2 : "hello", Data3 : "hi" }, Data4 : { Data5 : "this is Karan", } } I'm looking ...

The json_encode function is unexpectedly returning as an undefined value

After poring over several guides, I've been learning about how to use JSON to pass values from PHP to JS. But now I'm facing a little issue. Currently, in my jquery-function (don't pay attention to 'id: 1', it's there for a di ...

Struggling to align elements in React/JS/M?

My challenge is aligning the elements in the middle of my page. I aim to have 3 elements per row, with n rows depending on the number of "VideoBox" components. It's crucial that these elements fit within the lettering of the P R O F E S S I O N A L ...

Ordering tables in Knockout.js based on either values or alphabetically

I have a dataset in tabular form and I've implemented a knockout binding handler for sorting the table data upon clicking. The current functionality sorts the values, but I need to enhance it to sort groups of data with the same value alphabetically b ...

Maintain the div's aspect ratio by adjusting its width according to its height

I am seeking a way to maintain the width of the .center div in relation to its height, following a 4:3 aspect ratio (4 units wide for every 3 units high). The height of the div should be set to 100%, and I also need to align the div horizontally at the cen ...

Is there a way to display only the first x characters of an HTML code while disregarding any tags present within

When I work with a text editor, it generates HTML code that I save in the database. On another page, I need to display only the first 100 characters of the text without counting the HTML tags. For instance, let's say this is the HTML code saved in th ...

Unlimited Lunch Options and Navigational Links

Looking for help with displaying the ul for MAINTENANCE and referencing specified classes from a CSS style sheet that are working elsewhere. However, the sub menu for MAINTENANCE is not showing up. Any suggestions? /* * Superfish v1.4.8 - jQuery menu w ...

Creating dynamic tables with jquery mobile

When the screen width decreases, I need to find a way to position 3 tables below each other without using float or breaking the jquery mobile layout. Using float: left; on the surrounding containers of each table is not an option as it disrupts the jquery ...

Utilize jQuery to interact with a Web API web service

Okay, so go ahead and roast me in 27 different languages if you want, but here's my dilemma: I've delved into creating a web service using the .NET 4 Web API. I've coded a method named GetTransaction that simply returns a string. It's ...

"The issue with the nested nth-child property is that it only affects the first element it is applied to

Having trouble with the nth-child property. The issue lies with the #subnav element. I'm unsure why nth-child isn't working as expected (supposed to change border color and width). Here's the problem and code snippet : <div class=" ...

Creating Structured Lists with HTML Columns

Can you assist me in achieving a single column layout for all the bullet points, as I would like to experiment with various designs? Below is what my current display looks like and how I envision it to be presented: https://i.stack.imgur.com/NhMCC.jpg Pl ...

Is it possible for me to utilize code blocks within the head content and link tags to make reference to specific themes

I am currently in the process of developing an ASP.NET application using themes. I have successfully assigned a theme to the application via the web config file. One issue I am facing is trying to reference a bookmark icon located within the themes direct ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Guide to Helping Users Customize JavaScript and CSS Files before Exporting as Embed Code

I have a vision to create a unique platform where users have the ability to log in to a customized dashboard, tailor their preferences, and then generate an embeddable code for age verification pop-ups on their websites. To kickstart this project, I'v ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

What is the best way to capture the current URL and store it in a variable using VB and ASP.NET?

There is a form available for users to fill out and submit, and I have VB code that converts the submitted form into an email sent to me. In order to identify which page the submission is coming from, I am looking to assign the current URL to a variable th ...

Is it possible to dynamically alter CSS using PHP?

Here's a little query on my mind. Is it possible to dynamically alter the content of a CSS style using PHP in this manner? <?php header("Content-type: text/css; charset: UTF-8"); $color = "red;"; ?> header { color:<?php print $co ...

Stylish Zigzag Border with a Patterned Background

Recently, I've been experimenting with creating a header that features a unique zigzag border. Traditionally, this effect is achieved using images to achieve the desired look. (1) I am curious if there is a way to implement a cross-browser compatible ...