The floating label effect will be removed when the required attribute is removed as well

Is there a method to achieve a floating label effect in Bootstrap 4 even after removing the "required" attribute from the input field?

$(document).ready(function() {
  $('.form-group input').on('focus', function() {
    $(this).siblings('label').addClass('active');
  });

  $('.form-group input').on('blur', function() {
    if (!$(this).val() && !$(this).attr('required')) {
      $(this).siblings('label').removeClass('active');
    }
  });
});
.appointment {
  padding-top: 49px;
  margin-bottom: 30px;
}

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

a:hover {
  color: blue;
  transition: .5s;
}

.form-group input {
  padding: 10px;
  border: 1px solid #ced4da;
  position: relative;
  z-index: 1;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1rem;
  color: gray;
  pointer-events: none;
  transition: 0.2s ease-out all;
  z-index: 2;
  border: 1px solid transparent;
  padding-left: 10px;
}

.form-group input:focus,
.form-group input:valid {
  border-color: #ced4da;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-group input:focus+label,
.form-group input:valid+label {
  top: 0;
  font-size: 0.75rem;
  color: #555;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<form>
  <div class="form-group">
    <div class="row">
      <div class="col">
        <input type="text" id="firstname" name="firstname" class="form-control" required>
        <label for="firstname">First Name</label>
      </div>
      <div class="col">
        <input type="text" id="middlename" name="middlename" class="form-control">
        <label for="middlename">Middle Name</label>
      </div>
      <div class="col">
        <input type="text" id="lastname" name="lastname" class="form-control" required>
        <label for="lastname">Last Name</label>
      </div>
    </div>
  </div>
  <div class="text-center">
    <label>
      <a href="{{ route('index') }}"><i class="icofont-bubble-left"></i> Back to Home</a>
    </label>
  </div>
  <br>
</form>

I am encountering an issue with my script where the label is already floating even when the input field is not focused or reloaded. I'm unsure what might be causing this behavior.

Answer №1

This solution involves a simple workaround - instead of using the :valid pseudo class, modify the selector to utilize a class .valid and then dynamically toggle that class on the input field based on whether it is empty or not.

$(document).ready(function() {
  $('.form-group input').on('blur', function() {
    $(this).toggleClass('valid', $(this).val() !== '');
  });
});
.appointment {
  padding-top: 49px;
  margin-bottom: 30px;
}

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

.form-group .col {
  position: relative;
}

a:hover {
  color: blue;
  transition: .5s;
}

.form-group input {
  padding: 10px;
  border: 1px solid #ced4da;
  position: relative;
  z-index: 1;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1rem;
  color: gray;
  pointer-events: none;
  transition: 0.2s ease-out all;
  z-index: 2;
  border: 1px solid transparent;
  padding-left: 10px;
}

.form-group input:focus,
.form-group input:valid {
  border-color: #ced4da;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-group input:focus+label,
.form-group input.valid+label {
  top: 0;
  font-size: 0.75rem;
  color: #555;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<form>
  <div class="form-group">
    <div class="row">
      <div class="col">
        <input type="text" id="firstname" name="firstname" class="form-control" required>
        <label for="firstname">First Name</label>
      </div>
      <div class="col">
        <input type="text" id="middlename" name="middlename" class="form-control">
        <label for="middlename">Middle Name</label>
      </div>
      <div class="col">
        <input type="text" id="lastname" name="lastname" class="form-control" required>
        <label for="lastname">Last Name</label>
      </div>
    </div>
  </div>
  <div class="text-center">
    <label>
      <a href="{{ route('index') }}"><i class="icofont-bubble-left"></i> Back to Home</a>
    </label>
  </div>
  <br>
</form>

Answer №2

The culprit in this code snippet lies within the CSS line provided here:

.form-group input:valid+label 

This specific CSS rule formats the label in a certain way when the associated field is considered valid and not required.

Additionally, if you are working on a demo that utilizes Bootstrap's CSS framework, make sure to include the following line of code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

$(document).ready(function() {
  $('.form-group input').on('focus', function() {
    $(this).siblings('label').addClass('active');
  });

  $('.form-group input').on('blur', function() {
    if (!$(this).val() && !$(this).attr('required')) {
      $(this).siblings('label').removeClass('active');
    }
  });
});
.appointment {
  padding-top: 49px;
  margin-bottom: 30px;
}

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}

a:hover {
  color: blue;
  transition: .5s;
}

.form-group input {
  padding: 10px;
  border: 1px solid #ced4da;
  position: relative;
  z-index: 1;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1rem;
  color: gray;
  pointer-events: none;
  transition: 0.2s ease-out all;
  z-index: 2;
  border: 1px solid transparent;
  padding-left: 10px;
}

.form-group input:focus,
.form-group input:valid {
  border-color: #ced4da;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-group input:focus+label
 {
  top: 0;
  font-size: 0.75rem;
  color: #555;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<form>
  <div class="form-group">
    <div class="row">
      <div class="col">
        <input type="text" id="firstname" name="firstname" class="form-control" required>
        <label for="firstname">First Name</label>
      </div>
      <div class="col">
        <input type="text" id="middlename" name="middlename" class="form-control">
        <label for="middlename">Middle Name</label>
      </div>
      <div class="col">
        <input type="text" id="lastname" name="lastname" class="form-control" required>
        <label for="lastname">Last Name</label>
      </div>
    </div>
  </div>
  <div class="text-center">
    <label>
      <a href="{{ route('index') }}"><i class="icofont-bubble-left"></i> Back to Home</a>
    </label>
  </div>
  <br>
</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

Guide on sending MySQL query results as JSON data using Ajax

I'm having trouble figuring out how to pass the results of a MySQL query into an HTML page using AJAX and JSON. I have the following code in ajax2.php: $statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2") ...

The container is hugging the edges of the screen a little too closely in Firefox

Using Bootstrap 5.0.2, I've implemented custom CSS with the code snippet below: @media (min-width: 1680px) { .container, .container-fluid { box-sizing: border-box !important; max-width: 1750px; } } When viewing the page on Chrome, every ...

Display personalized content over images utilizing the jQuery galleria plugin

Hey there, I've been successfully using the jquery galleria plugin, but now I'm looking to add some custom content and links that will display in the center of the image. Is it possible to achieve this with galleria? Your insights would be greatl ...

Having trouble with the open and create new post button not functioning properly

The submit post button, user name, and logout button are not functioning properly. Can anyone assist with this issue? F12 and jsintrc are not providing any useful information. Below is the HTML code for the create new post button which should direct to a ...

The @ViewChild in Angular 2 seems to be unable to detect the BaseChartDirective from the ng2-charts

I'm currently using ng2-charts v1.5.0 and I'm facing an issue with updating the chart data after a click event. Despite following suggestions from other sources, I am unable to get it to work properly. Here is a snippet of my code: <div styl ...

Strategies for smoothly navigating the page to a specific div every time

Currently, I am working on a form that requires submitting multiple child forms. To enhance user experience, I have incorporated jQuery functionality to display a message at the top of the page upon each submission. Now, my goal is to implement a feature w ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

Is there a way for me to properly initiate the Material UI Modal from the parent component?

This is the main component: import React from 'react'; import ChildModal from 'ChildModal'; const MainComponent = () => ( <div> <span>Click </span> <a>HERE TO OPEN MODAL</a> <div> ); ...

Tracking progress within an HTML table

I am facing an issue with a table that is designed to display progress bars for each method or task stored in the database. These progress bars are determined by two dates: the startDate and endDate. However, I have noticed that the progress bar only funct ...

"Instead of opening the page in a popup window, use window.open to open it in a new tab

I am attempting to open a new popup window using this JavaScript code: window.open(myUrl, ""); However, some users are experiencing the page opening in a new tab instead of a popup window. Does anyone know why this may be happening? ...

Verify whether the headers in the CSV file correspond; if they do, proceed with parsing, otherwise halt

I am currently working on implementing validation for a specific .CSV format before proceeding with parsing using PapaParse. My plan is to first check the headers and verify if they match the following: Extension, company, name If the headers match, the ...

Is it possible for a MySQL loop to only delete the first entry?

My MySQL looping is not working properly when I click the second button to get their id and continue with the rest of the process. Why is this happening? $(document).ready(function() { $("#deleteSchedule").click(function (e) { e.preventDefault(); ...

The intricacy of the jQuery each function and its interaction with $(this

EXPLANATION: I am working with two elements, each containing a set of options. The first element has options with db-ids as values, acting as parent categories. The second element is filled with options where the parent db-ids are their values and their o ...

Attempting to insert form information into a database by making an Ajax call with PHP

I am facing issues with adding data to a local database using my form. Here is my addproducts.php page: <?php $title = "Products"; include("Header.php"); include("PHPvalidate.php"); ?> <script src="AjaxProduct.js"></script> <art ...

Using a directive to insert HTML content from a separate file into a div element

As a newcomer to angularjs, I am experimenting with appending html from another file using my directive. The goal is to only do this if there is a successful response from the server after an http request. The current approach involves defining my directi ...

Issue with Vue: Calling method instantly when using :mouseover in v-for within a component

Whenever I try to incorporate :mouseover in a v-for loop within the <component>, I encounter an issue. The method assigned to the :mouseover event is triggered for each element, rather than just for the hovered elements. <Single-technology ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Can you explain the functionality of a Radius Manager and how I can personalize it to suit my needs

Can you explain what a Radius Manager is and how I can customize it? My company wants me to create a website based on their radius manager, and they've given me three steps for the login page: 1- Verify username and password for authentication 2- Ch ...

Creating an Array in jQuery to Store Selected and Unselected Items

Looking for a way to collect all selected items from a form and save them in an array, as well as gather the non-selected elements and store them in a separate array. <select multiple id="conditionBad" name="conditionBad"> <option class=" ...