Is the div not visible? Only prepend then

Looking to prepend a div only when the specified conditions are met.

$(".loginForm").submit(function() {
    var username = $("input.username").val();
        var password = $("input.password").val();
        var errorvisible = $("body").has(".alert.error");
    if (!username || !password && errorvisible == false) {
        $('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");

        setTimeout(function() {
            $('.error.alert').fadeOut('1000', function() {
                $('.error.alert').remove();
            });
        }, 6000);

        event.preventDefault();
    }

});

Currently attempting to implement the functionality so that the jQuery code executes only if the error message is not already displayed. However, facing issues with the implementation.

        <div class="pageCont">

        <div class="title">
            <h1>LetsChat</h1>
            <h4>The new way of interaction.</h4>
        </div>

        <div class="login box">
        <form method="POST" action="#" class="loginForm">
            <input type="text" class="loginInput username" placeholder="Aquinas Email or Number" /><br>
            <input type="password" class="loginInput password" placeholder="Password" /><br>
            <div class="checkBox">
                <input type="checkbox" id="checkBoxLink">
                <label for="checkBoxLink">Remember Me</label>
                <a href="forgotpass" class="forgotpass cfix">Forgotten your password?</a>
            </div>
            <input type="submit" value="Submit" class="login btn green" />
            <input type="reset" value="Clear Fields" class="reset btn green" />
        </form>
        </div>
        <div class="signup box">
            <form method="POST" action="#" class="signupForm">
                <input type="text" class="signupInput" placeholder="First Name" /><br>
                <input type="text" class="signupInput" placeholder="Last Name" /><br>
                <input type="text" class="signupInput" placeholder="Aquinas Email" /><br>
                <input type="password" class="signupInput" placeholder="Password" /><br>
                <input type="submit" class="purple btn signup" value="Sign Up Today!">
            </form>
        </div>
    </div>

Answer №1

If I understand your question correctly, the following code should solve your issue:

  $(".loginForm").submit(function() {
    var username = $("input.username").val();
    var password = $("input.password").val();
    var errorvisible = $("body").has(".alert.error").length;

    if (!username || !password) 
    {
        if(errorvisible == 0)
            $('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");

        setTimeout(function() {
            $('.error.alert').fadeOut('1000', function() {
                $('.error.alert').remove();
            });
        }, 6000);

        event.preventDefault();         
    }
});

Answer №2

This particular block of code has been a staple in my programming arsenal for quite some time:

if(!$('#myFancyDiv').is(':visible')) {
    //you can add content before or perform any desired actions here
}

By the way, to clarify, this snippet verifies that 'myFancyDiv' is actually not visible.

Answer №3

To determine if the elements with class .error.alert exist, check their presence first before taking any action to create a new one.

$(".loginForm").submit(function() {
  var username = $("input.username").val();
  var password = $("input.password").val();
  var errorvisible = $("body").has(".alert.error");
  if (!username || !password && errorvisible == false) {

    if (!$('.error.alert').length) {
      $('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
      setTimeout(function() {
        $('.error.alert').fadeOut('1000', function() {
          $(this).remove();
        });
      }, 6000);
    }

    event.preventDefault();
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="#" class="loginForm">
  <input type="text" class="loginInput username" placeholder="Aquinas Email or Number" />
  <br>
  <input type="password" class="loginInput password" placeholder="Password" />
  <br>
  <div class="checkBox">
    <input type="checkbox" id="checkBoxLink">
    <label for="checkBoxLink">Remember Me</label>
    <a href="forgotpass" class="forgotpass cfix">Forgotten your password?</a>
  </div>
  <input type="submit" value="Submit" class="login btn green" />
  <input type="reset" value="Clear Fields" class="reset btn green" />
</form>

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

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Tips for sending eventData parameters to .on() by utilizing the .trigger() function from jQuery?

My event handler on the <select> element looks like this: select.on("change", null, { tbody: $("#tbody"), colspan: 5, onLoad: onLoadHandler, }, onSelectChange); Inside the onSelectChange function, I access these parameters via the event ...

Utilizing the jQuery library for flexible REST API requests with the incorporation

I'm currently utilizing jQuery getJSON to fetch posts from the WP API v2. There are some input fields that I'd like to make clickable, and then add extra parameters to the request URL. Here are some example requests: Posts - https://www.example ...

Does the Parent Tag style override the child tag style when hovering?

I am currently dealing with some style issues. How can I apply the styling of the parent tag to the child tag when hovering over it? Let's illustrate this with a simple example. .outer:hover { background: yellow; z-index: 1; position: relativ ...

Overlay Image on Card, Overflowing into Card Body

I currently have a webpage featuring cards. Each card includes a thumbnail at the top with an overlay. The main content of the card needs to be positioned outside of the overlay, but it ends up overflowing onto it. Take a look at the demo: https://codepe ...

Looking for a reliable jQuery plugin for editing images?

Currently, I am on the lookout for a reliable jQuery plugin that can facilitate image manipulation. I am interested in features such as enabling users to upload an image, crop and resize it, and make basic adjustments like brightness, contrast, color, an ...

What is the best approach for creating a Pagination component in React JS?

I recently started developing a web-app and I'm still learning about web development. I have received a backend response in JSON format with pagination information included: { "count": 16, "next": "http://localhost:800 ...

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

Customize the appearance of a hyperlink

I am having difficulty styling a link's title using jQuery-mobile. Each link represents a player with unique abilities. When the user hovers over a player, I want a tooltip to display their special ability. Despite trying various code samples, none ha ...

Loading JW Player inside a "pop-up window"

My query pertains to the implementation of FancyBox version on this stackoverflow post: http://stackoverflow.com/questions/8221253/loading-jw-player-inside-of-fancybox Specifically for this inquiry, I am seeking recommendations for the following situation ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

A guide on extracting the text attribute of an element using an index in jQuery

object.option[index].title = object.option[index].text I am looking to convert this JavaScript code into jQuery. Any assistance would be greatly appreciated. ...

Guide to making a dynamic clip mask with flowing trails on a digital canvas

I have successfully coded a dynamic path with trails similar to the one shown on However, when I try to replace ctx.fill() with ctx.clip(), nothing appears on the canvas. Here is the JavaScript code snippet I'm using – for the full code, visit http ...

JSON - When an Object's Value Matches

Within my JSON file, I have an object that contains an array of nested objects. I am looking for a way to trigger a function based on the value of a specific object. If the value matches a certain number, I want to display only those objects within a desig ...

Implementing a PHP redirection for an API after a jquery ajax get request results in a 302 status code

When I make a call to a PHP page using jQuery Ajax to connect to an API and get the request token, I then redirect back to the same page with a header. However, I am encountering a 302 error when returning a JSON encoded string. My main concern is how can ...

Unable to activate dropdown menu in html and css

Hi there, I'm facing an issue with hiding the dropdown-menu submenu. I tried using display: block !important;, but it didn't work. Even when I used display: none !important;, the dropdown menu still wouldn't disappear. I want the dropdown s ...

Submitting forms with Ajax using Jquery

I'm looking to utilize ajax to submit a form in the background. My attempt so far is as follows: <div class="form-horizontal" id="form"> <label for="name" class="control-label">Enter your name</label> <div class="controls ...

Ways to display console.log output in VS Code?

Sorry if this question is a bit unclear, but I'm struggling to figure out how to display the results from my console.log (line 14) in the console/terminal. I want to see the random RGB values generated for each column every time I click the button, bu ...

Utilize JSON FabricJS to incorporate image data seamlessly

Currently, I am working with the FabricJS canvas and my goal is to export the canvas as JSON. I have experimented with loading images using both new fabric.Image and fabric.Image.fromURL, and both methods have worked well for me. My next task is to obtai ...

There seems to be a styling issue in my CSS where the text element is consistently displaying one line below its corresponding label

When working with Rails 3.2.16 and incorporating Twitter Bootstrap into my forms using simple_form_for, I noticed that all of my text elements were showing up below and to the right of their labels, despite using the form-horizontal class. Here is a snippe ...