Field labels remain visible even when corresponding input fields or selection options are hidden

I have implemented a Bootstrap form with the form-floating class on the controls.

An issue arises when certain controls are hidden, causing the labels to remain visible and become congested. Oddly enough, this only occurs with some controls while others behave as expected. Despite identical code structure, this inconsistency puzzles me.

A noteworthy observation is that moving the hidden fields above the triggering field results in proper label hiding. However, upon relocating them back under the trigger, the labels resurface and overlap once more.

HTML:

<div class="form-floating mb-4">
    <select class="form-select" id="frmProjectInterconnect" required>
        <option value="" selected disabled></option>
        <option>Yes</option>
        <option>No</option>
    </select>
    <label for="frmProjectInterconnect">Project Interconnection Point</label>
</div>

<div class="form-floating mb-4">
    <input type="number" class="form-control" id="frmInterconnectionCapacity" required>
    <label for="frmInterconnectionCapacity">Interconnection Capacity (Mbps)</label>
</div>

<div class="form-floating mb-4">
    <select class="form-select" id="frmDedicatedOrShared" required>
        <option value="" selected disabled> </option>
        <option>Dedicated</option>
        <option>Shared</option>
    </select>
    <label for="frmDedicatedOrShared">Dedicated or Shared?</label>
</div>

<div class="form-floating mb-4">
    <input type="text" class="form-control" id="frmServiceProvider" required>
    <label for="frmServiceProvider">Service Provider</label>
</div>

Javascript:

$('#frmProjectInterconnect').change(function(){
    if($(this).val() == "Yes") {
        $("#frmInterconnectionCapacity").show();
        $("#frmInterconnectionCapacity").attr('required', '');
        $("#frmInterconnectionCapacity").attr('data-error', 'This field is required.');
        $("#frmDedicatedOrShared").show();
        $("#frmDedicatedOrShared").attr('required', '');
        $("#frmDedicatedOrShared").attr('data-error', 'This field is required.');
        $("#frmServiceProvider").show();
        $("#frmServiceProvider").attr('required', '');
        $("#frmServiceProvider").attr('data-error', 'This field is required.');
    } else {
        $("#frmInterconnectionCapacity").hide();
        $("#frmInterconnectionCapacity").removeAttr('required');
        $("#frmInterconnectionCapacity").removeAttr('data-error');
        $("#frmDedicatedOrShared").hide();
        $("#frmDedicatedOrShared").removeAttr('required');
        $("#frmDedicatedOrShared").removeAttr('data-error');
        $("#frmServiceProvider").hide();
        $("#frmServiceProvider").removeAttr('required');
        $("#frmServiceProvider").removeAttr('data-error');
    }
});

https://i.sstatic.net/b9xsi.png

https://i.sstatic.net/OLFFo.png

Answer №1

Attempt to display/hide the parent container

$('#frmProjectInterconnect').change(function(){
    if($(this).val() == "Yes") {
        $("#frmInterconnectionCapacity").parent().show();
        $("#frmInterconnectionCapacity").attr('required', '');
        $("#frmInterconnectionCapacity").attr('data-error', 'This field is required.');
        $("#frmDedicatedOrShared").parent().show();
        $("#frmDedicatedOrShared").attr('required', '');
        $("#frmDedicatedOrShared").attr('data-error', 'This field is required.');
        $("#frmServiceProvider").parent().show();
        $("#frmServiceProvider").attr('required', '');
        $("#frmServiceProvider").attr('data-error', 'This field is required.');
    } else {
        $("#frmInterconnectionCapacity").parent().hide();
        $("#frmInterconnectionCapacity").removeAttr('required');
        $("#frmInterconnectionCapacity").removeAttr('data-error');
        $("#frmDedicatedOrShared").parent().hide();
        $("#frmDedicatedOrShared").removeAttr('required');
        $("#frmDedicatedOrShared").removeAttr('data-error');
        $("#frmServiceProvider").parent().hide();
        $("#frmServiceProvider").removeAttr('required');
        $("#frmServiceProvider").removeAttr('data-error');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4944445f585f594a5b6b1e051a0518">[email protected]</a>/dist/css/bootstrap.min.css"></link>
<div class="form-floating mb-4">
    <select class="form-select" id="frmProjectInterconnect" required>
        <option value="" selected disabled></option>
        <option>Yes</option>
        <option>No</option>
    </select>
    <label for="frmProjectInterconnect">Project Interconnection Point</label>
</div>

<div class="form-floating mb-4">
    <input type="number" class="form-control" id="frmInterconnectionCapacity" required>
    <label for="frmInterconnectionCapacity">Interconnection Capacity (Mbps)</label>
</div>

<div class="form-floating mb-4">
    <select class="form-select" id="frmDedicatedOrShared" required>
        <option value="" selected disabled> </option>
        <option>Dedicated</option>
        <option>Shared</option>
    </select>
    <label for="frmDedicatedOrShared">Dedicated or Shared?</label>
</div>

<div class="form-floating mb-4">
    <input type="text" class="form-control" id="frmServiceProvider" required>
    <label for="frmServiceProvider">Service Provider</label>
</div>

Edit: When the dropdown option is at the end and we don't hide the parent container, it seems like the labels are hidden but they are actually behind the dropdown. I have added a 1-second delay to hide the dropdown, making the labels visible. Refer to the updated code snippet below.

$('#frmProjectInterconnect').change(function(){
        if($(this).val() == "Yes") {
            $("#frmInterconnectionCapacity").show();
            $("#frmInterconnectionCapacity").attr('required', '');
            $("#frmInterconnectionCapacity").attr('data-error', 'This field is required.');
            $("#frmDedicatedOrShared").show();
            $("#frmDedicatedOrShared").attr('required', '');
            $("#frmDedicatedOrShared").attr('data-error', 'This field is required.');
            $("#frmServiceProvider").show();
            $("#frmServiceProvider").attr('required', '');
            $("#frmServiceProvider").attr('data-error', 'This field is required.');
        } else {
            $("#frmInterconnectionCapacity").hide();
            $("#frmInterconnectionCapacity").removeAttr('required');
            $("#frmInterconnectionCapacity").removeAttr('data-error');
            $("#frmDedicatedOrShared").hide();
            $("#frmDedicatedOrShared").removeAttr('required');
            $("#frmDedicatedOrShared").removeAttr('data-error');
            $("#frmServiceProvider").hide();
            $("#frmServiceProvider").removeAttr('required');
            $("#frmServiceProvider").removeAttr('data-error');
            
            setTimeout(() => {
              $('#frmProjectInterconnect').hide();
            }, 1000);
        }
    });
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac8c5c5ded9ded8cbdaea9f849b8499">[email protected]</a>/dist/css/bootstrap.min.css"></link>

    <div class="form-floating mb-4">
        <input type="number" class="form-control" id="frmInterconnectionCapacity" required>
        <label for="frmInterconnectionCapacity">Interconnection Capacity (Mbps)</label>
    </div>

    <div class="form-floating mb-4">
        <select class="form-select" id="frmDedicatedOrShared" required>
            <option value="" selected disabled> </option>
            <option>Dedicated</option>
            <option>Shared</option>
        </select>
        <label for="frmDedicatedOrShared">Dedicated or Shared?</label>
    </div>

    <div class="form-floating mb-4">
        <input type="text" class="form-control" id="frmServiceProvider" required>
        <label for="frmServiceProvider">Service Provider</label>
    </div>
    <div class="form-floating mb-4">
        <select class="form-select" id="frmProjectInterconnect" required>
            <option value="" selected disabled></option>
            <option>Yes</option>
            <option>No</option>
        </select>
        <label for="frmProjectInterconnect">Project Interconnection Point</label>
    </div>

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

Step-by-step guide on mocking a method within a method using JEST

Currently, I am facing a challenge in unit testing a method named search. This method consists of three additional methods - buildSearchParameter, isUnknownFields, and readAll. I am looking to mock these methods but I am uncertain about the process. Can ...

Encountering problem while opening a PDF document in an AngularJS mobile application built with Cordova

Currently I am working on implementing the functionality to open PDF documents in AngularJS on desktop and mobile devices. I have been referring to the following resource: Open a PDF in a new window of the browser with AngularJS I have implemented a simila ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Is it possible to use HTML alone in Bootstrap 5 to link a button to display a toast notification?

I'm working on a Bootstrap page that includes a button and a toast element sourced from the Bootstrap documentation. The documentation states that I need to initialize the toast in JavaScript during page load. My goal is to have the toast appear when ...

What is the best way to include multiple views in a main HTML template in Angular?

Is there a way to load two HTML files into a base HTML file? Essentially, I have a base HTML file with a header and content view, and I want to load different HTML files into each of them. Here is the base HTML file structure: <div class="container"> ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Is there a way to verify the react-query queries prior to running them?

Consider this scenario where I have a query to retrieve a list: const list = useQuery('list', fetcher); However, I require a pre-checking function before react-query triggers the execution. Something like this: const appQueryClient = new QueryCl ...

ng-bind-html behaving unexpectedly

index.html <div ng-bind-html="htmlElement()"></div> app.js $scope.htmlElement = function(){ var html = '<input type="text" ng-model="myModel" />'; return $sce.trustAsHtml(html); } However, when attempting to retrieve t ...

What is the method to obtain the dimensions of the browser window using JavaScript?

In my JavaScript code, I am trying to retrieve the browser window size and then set the size of a div element accordingly. I have two div elements that should adjust based on the window size. For example, if the window size is 568px, div1 should be 38% of ...

Continuous Scrolling with Callback Function in jQuery

I have implemented the infinite-scroll plugin, which replaces traditional pagination with ajax to fetch new pages. The issue I am facing is that jQuery functions do not recognize the new posts, causing certain functions like the ones below to stop working ...

How can the edit feature be implemented in AngularJS?

I am struggling with implementing an edit field in AngularJS. Can someone please help me with this? Here is the code for my CRUD operations: var app = angular.module('myApp', []) app.controller('myCtrl', ['$scope', functio ...

Is it possible to receive returned string values using fetch()?

I have implemented a fetch method in my separate register.js file to handle registration on the front end. However, I am encountering an error when trying to POST the data and receive the following message in the browser console: "Uncaught (in promise) Syn ...

Choosing the Right Project for Developing HTML/Javascript Applications in Eclipse

Whenever I attempt to build a webpage using eclipse, I am presented with two choices: -- A Javascript project -- A Static web project If I opt for the former, setting up run to open a web browser can be quite challenging. If I decide on the latter ...

Merging columns in Bootstrap 4 grid system

I have been working on creating a Bootstrap grid with the following structure: .facevalue { background: #ffffff61; font-family: Dubai; font-size: 18px; font-weight: 400; line-height: 30px; padding: 0 30px; border: 1px solid #e9e9e9; ma ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...

When trying to publish a new post using postman, the content including the title, message, and image is not displaying

I am currently learning how to build a REST API by following a tutorial. Below is an excerpt from my server.js file: import express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; ...

How can Vuejs be utilized to showcase data with the onChange event?

I'm working on a Vuejs component and I currently have this code snippet: <div class="col-sm-9"> <Select class="form-control" name="building" v-model="allBuild.id" @change="showBuilding($event)& ...

Merge together JQuery variables

I want to assign a unique number to each JavaScript variable and jQuery element in my code. Take a look at the snippet below: $("#insert1").click(function(){ var collegeId1=$("#collegeId1").val(); $.post('insert.php', {collegeId: colle ...

What is the best way to arrange an array using AngularJs or Javascript?

When a user makes a selection, I want to sort and display an array in alphabetical order. Specifically, when we render data from the backend, I would like to display the fullName in alphabetical order. The $scope.selectedControlOwner is the ng-click event ...

What is the method to have the text cursor within a text field start a few pixels in?

I need a text field with the cursor starting a few pixels (let's say 4) from the left-hand side. I am aware that this can be achieved by adjusting the size of the text field using padding, but I am curious if there is a way to resize the text box with ...