Instructions on implementing a floating label on a select2 dropdown menu

I am currently utilizing the select2 plugin for my select dropdowns on a webpage. I have multiple select dropdown boxes and I need to implement a floating label specifically for the selected dropdown.

Despite my efforts and searches, I have not been able to find the desired results I was hoping for.

Below is the code that I have been working with:

HTML

<div class="container">
  <div class="row">
    <div class="col-md-6 col-lg-6 col-sm-6">
      <label class="hor-menu visible-xs visible-xs control-label col-sm-1"></label>
      <div class="form-group form-md-line-input form-md-floating-label" style="margin-top: 13px;">
        <select name="cboNGrp" id="cboNGrp" class="form-control select2me input-xlarge" data-live-search="true" data-size="8"></select>
        <label class="form_control_1 head_ctrl_label" style="padding-top: 2px;">Type</label>
      </div>
    </div>
    <div class="col-md-6 col-lg-6 col-sm-6">
      <div class="form-group form-md-line-input head_ctrl">
        <label class="hor-menu visible-xs visible-xs control-label  col-sm-1"></label>
        <select name="cboEmrGrp" id="cboEmrGrp" class="select2me form-control input-xlarge"></select>
        <label class="form_control_1 head_ctrl_label">E / M</label>
      </div>
    </div>
  </div>
</div>

JS

$('.select2me').click(function(e){
    if($(this).find('select2-dropdown-open')) {
        $('label.head_ctrl_label').css('margin-top', '-25px'); 
    }
    e.preventDefault();
});

Image of user interaction with Dropdown selection

Image displaying bug where floating label applies to all dropdowns instead of just the selected one

Answer №1

Here's a helpful tip for you!

$('select').select2().on('select2:open', (elm) => {
    const targetLabel = $(elm.target).prev('label');
    targetLabel.addClass('selected');
}).on('select2:close', (elm) => {
    const target = $(elm.target);
    const targetLabel = target.prev('label');
    const targetOptions = $(elm.target.selectedOptions);
    if (targetOptions.length === 0) {
        targetLabel.removeClass('selected');
    }
});

Styling with SCSS

label {
    &.selected {
        top: 0;
        font-size: 11px;
        transform: translateY(0);
    }
    font-size: 16px;
    color: #dfdfdf;
    position: absolute;
    z-index: 1;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
    transition: all 0.2s ease 0s;
}

Check out this CodePen demo

Answer №2

To start using the Select2 bootstrap 5 theme, you need to first download and install it from here:

After installation, run the following npm command:

$('.select2me').select2({
    theme: "bootstrap-5",
});
            
$('.select2me')
    .parent('div')
    .children('span')
    .children('span')
    .children('span')
    .css('height', ' calc(3.5rem + 2px)');
$('.select2me')
    .parent('div')
    .children('span')
    .children('span')
    .children('span')
    .children('span')
    .css('margin-top', '18px');
$('.select2me')
    .parent('div')
    .find('label')
    .css('z-index', '1');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Styles -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2/dist/select2-bootstrap-5-theme.min.css" />
<!-- Or for RTL support -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2/dist/select2-bootstrap-5-theme.rtl.min.css" />

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2/dist/js/select2.min.js"></script>

<div class="form-floating">
  <select class="form-select select2me" id="floatingSelect"  aria-label="Floating label select example">
    <option selected>Open this select menu</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>
  <label for="floatingSelect">Works with selects</label>
</div>

Answer №3

Give this a shot:

$('.clickme').on('click', function(event){
   if($(this).has('dropdown-open')) {
      $(this).next('.label').css('top', '-15px'); }
      event.preventDefault();
});

Answer №4

Here is a CSS-only solution:

    <style>
    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered{
        float: right;
    }
    .control-label{
        z-index:11;
    }
    </style>

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

Issue with $.ajax request even when valid JSON data is provided

Below is the code I am currently using: var jsonURL = "http://www.sodexo.fi/ruokalistat/output/daily_json/440/2013/10/25/fi"; var request = $.ajax({ url: jsonURL, dataType: "json", type: "GET" }); request.done(functio ...

Adding images to .xsl using XML

I have created a unique "blog" using XML and XLST. The format of the blog is as follows: <post id="1" category="Miscellaneous"> <ptitle>MiG-21</ptitle> <psubtitle>Mikoyan-Gurevich MiG-21</psubtitle> <image></image& ...

Ensuring Consistent Vertical Spacing for CSS-Animated Bootstrap 5 Navbar Toggler Buttons in All Browsers

After watching a tutorial on implementing a custom Navbar toggler button in Bootstrap 5, I decided to try it out myself. However, I encountered an issue with the spacing between the three bars that make up the toggler button - the spacing looked different ...

Finding the height of a dynamic div in ReactJS when no CSS height is set

I'm encountering an issue when trying to determine the height of a dynamically created div that doesn't have a defined CSS height property. I'm working with React JS and have attempted to use jQuery, pure JavaScript, and React tools to acces ...

Can you show me how to send data from jQuery to Flask?

I am facing a challenge with passing values from three inputs back to a function within my app, specifically when rendering the index.html using Flask. Below are the inputs: <form method="POST" action="/"> <sma ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Angular 2: Issue with disabled functionality not functioning correctly

In my TypeScript code, I have created a boolean variable called readOnlyMode. When this variable is set to true, all elements should be disabled. To achieve this, I am using [disabled]="readOnlyMode" in the HTML for elements that need to be disabled. Howev ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

Struggling with implementing autocomplete and saving a nested form in Rails 5 with AJAX?

In this team model, there are numerous users associated with teams through the has_many :through relationship. There is a need to implement autocomplete functionality for user search and nested field addition upon selecting a user. app/controllers/teams_c ...

What is the best way to incorporate parallax scrolling in the center of a webpage?

I am trying to implement a parallax scrolling effect in the middle of my page, but it seems to be causing issues once I reach that section while scrolling. I attempted to use intersection observer, but unfortunately, it did not resolve the problem. const ...

the child div within a Bootstrap 3 column is not being properly styled

Experiencing a strange issue with a relative div within a column in Bootstrap 3. Here's my code: <div class="col-lg-6"> <div class="large" style="background: url(img/bg.jpg);"> <h1 class="grid-header">Content 1</h1> ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...

Executing a snippet of Bootstrap 5 code under specific circumstances

I need to execute different code blocks based on the window width. When the width is 500px or more, I want to run a specific block of code, and when it's 499px or less, I need another block of code to run. How can I achieve this? For widths of 500px ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

Instead of using an ID in javaScript, opt for $(this) instead

Is there a way to utilize $(this) instead of an ID in the option select function in javaScript? var tot = 5 * ($( "#firstOne option:selected" ).text()); In the scenario mentioned above, I aim to substitute $(this) for #firstOne, allowing this functional ...

Vue-loader component experiencing issues with applying dynamic CSS styling

I'm working with a Vue Component and I want to enhance it by binding a color to a specific message. Initially, I attempted to achieve this using a binding like :style="styles" However, I encountered the following error: The property or method "st ...

Obtain a collection of chosen dates from the availability scheduler

I am currently working on an availability calendar where users can select multiple dates. While I have successfully been able to retrieve the value of each individual cell, I am facing difficulty in getting an array of values for all the cells selected. ...

What is the best way to implement a keypress event in this code?

As a JavaScript and jQuery newbie, I have a question regarding adding a simple key press action to this code. How can I implement functionality where pressing the Right Arrow key takes me to the next image, and pressing the Left Arrow key takes me to the p ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...