How can you customize the appearance of the input box in Select2 after a selection has been made

I have been attempting to apply a CSS style to the select2 box once the user has selected a value. However, I am struggling to find a way to achieve this. If I make changes directly to the CSS file, the changes persist even when the placeholder is displayed and no selection has been made. Adding a class directly to the HTML does not produce the desired results.

What I need is for the following CSS to be applied when a value is selected, meaning when the placeholder is replaced with the selected value after the allowClear event is triggered. Is it possible to achieve this? I have searched extensively but haven't found a solution yet, and as I am relatively new to this, please forgive me if this seems like a basic question (English is not my primary language).

border-bottom: 1px solid #b3b3b3 !important;

This is the script I am using:

PHP/HTML

<select id="filteruser" class="select_test">
   <?php while ($row33 = $result33->fetch_assoc()) { ?>
        <option value="<?php echo $row33['user']; ?>"><?php echo $row33['name']; ?></option>
    <?php } $stmt33->close();?>
    
    </select>

The Select jQuery Script

<script type="text/javascript">
    $(document).ready(function () {
$("#filteruser").select2( {
    placeholder: "Filter user",
    allowClear: true
    } );
$('#filteruser').val('<?php echo $_SESSION['user']; ?>'); // Select the option with a value of 'the current filter'
$('#filteruser').trigger('change'); // Notify any JS components that the value changed

} );
</script>

Edit: HTML Output Console

 <select id="filteruser" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true">
            <option></option> 
        <option value="123">name3</option>
            <option></option> 
        <option value="124">name4</option>
            <option></option> 
        <option value="125">name5</option>
            <option></option> 
      
        
    </select><span class="select2 select2-container select2-container--default select2-container--below select2-container--open select2-container--focus" dir="ltr" style="width: 51px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-labelledby="select2-filteruser-container" aria-owns="select2-filteruser-results" aria-activedescendant="select2-filteruser-result-cx2p-123296"><span class="select2-selection__rendered" id="select2-filteruser-container"><span class="select2-selection__placeholder">Filter user</span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

Answer №1

In order for the options to work correctly, you need to include: selectionCssClass:

$('#filteruser').select2({
      selectionCssClass: 'my-class-section'
    });

Make sure to add the following CSS as well:

.my-class-section{
  border-bottom: 1px solid #b3b3b3 !important;
}

Answer №2

Implementing a JavaScript event listener oninput allows for the execution of a function when an input is made, as shown in the code snippet below:

function updateBorder() {
  document.getElementById("example").style.borderBottom = "1px solid #b3b3b3";
}
select {
  outline: none;
  border: none;
}
<select oninput="updateBorder()" id="example">
  <option value="0">Select item:</option>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>

Answer №3

After doing some research, I discovered a solution that worked for me. By using jQuery, I was able to target an existing class and append another class to it. This allowed me to apply specific styles to the select box.

$('.select2').addClass('someclass')

I found the solution on this page:

How to add two classes to an existing class with jquery?

Appreciate all the assistance from everyone!

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

When using Material UI, I ran into an issue where my Card Component was being added to my Appbar. To improve user interaction, I desire for the cards to only appear once

The formatting of the naming conventions is incorrect. Please disregard those. Snippet of code for the Appbar: const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1 }, title: { flexGrow: 1 } })); export default function Appp() ...

Receiving a blank request payload despite implementing a body parsing middleware

I am currently working on setting up a login system, and I have a form that sends a post request to my webpack dev server. This server then proxies the request to my actual server. Here is the function responsible for handling the form submission and send ...

Combining $var positions within a PHP loop

Currently, I have a PHP script that is assisting me in generating code for a script: <script> (function($){ <?php foreach($buttons as $button) { // Loop through all available buttons ?> // When button one is clicked $('.butto ...

What is the best way to identify the source element that triggers an AJAX request within the "ajaxComplete" event handler?

I am currently working on an AJAX-based website where I need to keep a history of all requested pages made through AJAX calls. After some research, I found the Histroy.js library which helps me manage the state effectively. However, my challenge lies in id ...

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

Sending a JSON object as a string to PHP

I am currently using a JQuery script to manipulate an image. While most functions are working correctly, I am facing issues with returning data to PHP. Despite trying various examples from Stackoverflow, I have not been able to successfully return the data ...

The HTML5 onclick function is not functioning properly on the button

My HTML file includes a button with the id "botonRegistro" that should call a function when clicked. However, nothing happens and no alerts are displayed. I'm not sure why this button is not working while other buttons do. <!DOCTYPE html> <h ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

How can objects in JavaScript be combined only if they have been defined?

As I delve into the world of JavaScript, I find myself in need of merging four objects together while ensuring that the resulting object does not contain any "undefined" values. My current approach to this task looks like this: let result = {}; resul ...

What could be causing issues with my Ajax and JavaScript functionality?

While developing a website to search through my python database, I encountered an issue. The non-JavaScript version was functioning flawlessly. However, when attempting to implement AJAX so that the page would not have to be refreshed each time, I faced ...

Once the maximum total of all input fields has been reached, prevent any further input in the remaining

I run an online store where I offer a box of assorted flavor bagels with a maximum of 12 flavors per box. Each flavor has its own number input field, as seen in the screenshot linked below. https://i.sstatic.net/eSU09.png While I have successfully used J ...

What is the process for placing the back button on the left side in Ionic?

I am working on a project with Ionic framework and I need to align the back button to the left in the header. Here is the code snippet: <ion-header-bar class="bar-positive" align-title="left" > <h1 class="title" style="text-align: center">More ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

Utilize Google Tag Manager to Safely Gather Specific Data

My current project involves capturing values from a <select> element, sending them to the Data Layer, and then forwarding them to an Analytics account via Google Tag Manager. The source code I'm trying to extract values from includes a dynamic s ...

What are the best methods for rebooting a Node.js project?

As a developer with over 8 years of experience in PHP, I find myself needing to make changes to a live Node.js project, despite not being a Node.js developer myself. The task at hand is simply to change a payment gateway token, which should be a straightfo ...

Selecting Elements with JQuery

Hey there, I'm a beginner and I'm facing an issue with selecting an element within my navigation list <ul class="subnav"> <li><a href="#">Link 1</a><span class="sub">Description 1</span></li> <li>& ...

Delete elements from the Document Object Model

I have a situation where I am dynamically pushing components to the DOM in Angular 2. However, I am facing an issue with removing old components whenever a new set is pushed to the DOM. When I try to remove an individual component, it works fine. But when ...

issue with transferring a function from a parent component to a child component

While attempting to pass a function from the parent component to the child component, I encountered an issue that I am struggling to resolve. Every time I try to pass props to the child component, it doesn't seem to work and gives me the following err ...

The input value does not update in the controller when using AngularJS ng-model

Why is it that when I print out console.log($scope.inputvalue), the variable does not update with the values I enter in the input field? Did I misunderstand the purpose of ng-model? If so, how can I pass a value from the view to the controller? (functi ...