Adjust the dropdown width on a bootstrap form to match the size of the textbox

In order to maintain a combined width of 450px, I have two textboxes.

One textbox includes a dropdown menu while the other does not.

Both textboxes are part of an input group.

The dropdown can switch between either textbox at any time.

I need the width of the dropdown to match the width of the first textbox.

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

Even if the overall width is adjusted to 700px in the future, the dropdown should adjust accordingly.

<!doctype html>
<html lang="en">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>

<body>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

  <div class="dropdown selection-1d  input-group" style="width:450px">
      <input type="text" class=" form-control" data-bs-toggle="dropdown" value="All Fruits" aria-expanded="false" data-bs-auto-close="outside" readonly>
      
      <input type="text" class=" form-control" value="All Fruits" aria-expanded="false">
      
    <div class="dropdown-menu p-0">
      <div class="list-group">
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit1 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit2 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit3 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit4 </label>
      </div>
    </div>
  </div>

</body>

</html>

Answer №1

Here's a JavaScript snippet that adjusts the width of dropdown menus based on the data-bs-toggle sibling element.

I've included a second set of dropdowns with a larger width to demonstrate the concept.

The code is well-documented for clarity.

// Locate all dropdown menus within the page
let dropdown_menu = document.querySelectorAll('.dropdown-menu');

// Iterate through each menu
dropdown_menu.forEach(dd => {
  // Find the parent container element
  let parent = dd.parentElement;

  // Check if the parent has the input-group class
  if (parent.classList.contains('input-group')) {
    // Get the width of the element with the data-bs-toggle attribute
    let input_parent = parent.querySelector('[data-bs-toggle]').offsetWidth;
    // Set the width of the dropdown menu
    dd.style.width = input_parent + 'px';
  }

});
<!doctype html>
<html lang="en">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>

<body>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>



  <div class="dropdown selection-1d input-group" style="width:450px">

    <input type="text" class="form-control" data-bs-toggle="dropdown" value="All Fruits" aria-expanded="false" data-bs-auto-close="outside" readonly>

    <input type="text" class="form-control" value="All Fruits" aria-expanded="false">

    <div class="dropdown-menu p-0">
      <div class="list-group">
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit1 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit2 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit3 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit4 </label>
      </div>
    </div>
  </div>
  
  
  <div class="dropdown selection-1d input-group" style="width:700px">


<input type="text" class="form-control" data-bs-toggle="dropdown" value="Value" aria-expanded="false" data-bs-auto-close="outside" readonly>

<input type="text" class="form-control" value="Here is a long one" aria-expanded="false">

    
    <div class="dropdown-menu p-0">
      <div class="list-group">
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit1 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit2 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit3 </label>
        <label class="list-group-item">
          <input class="form-check-input me-1" type="checkbox" value=""> Fruit4 </label>
      </div>
    </div>
  </div>



</body>

</html>

EDIT

Using jQuery

$(document).ready(function() {
  $('.dropdown-menu').each(function() {
    $prev_sib_width = $(this).prevAll('[data-bs-toggle]').outerWidth();

    if ($prev_sib_width) {
      $(this).width($prev_sib_width);
    }

  });
});
<!doctype html>
<html lang="en>"

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

Exploring the Features of PrimeNG Table Component in Angular 8

After attempting to implement p-table (PrimeNG table) in my Angular project and importing all necessary dependencies and modules using the CLI, I encountered the following error: ERROR: The target entry-point "primeng/table" has missing dependencies: - @ ...

Divide the information in the table across several pages for easier printing

I have encountered an architectural challenge with my server-side React app. The app renders charts and tables with page breaks in between to allow a puppeteer instance to print the report for users in another application. The issue I'm facing is mak ...

Arranging Bootstrap Grids within Laravel

On my current web page, I have implemented Bootstrap Grids as seen in the image below. Check out My Bootstrap Grid Layout However, I am aiming to achieve a grid layout similar to the one shown in the picture with a red indicator. Here is the Desired Boo ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Customizing Column Background Color with AngularJS

https://i.sstatic.net/OHFFF.png My current webapp highlights the day of the week on a table for the current day and the day two weeks from now. However, I'm facing an issue with adjusting the highlight if either of these days falls on a holiday. Curr ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

In a carousel slider, the height and width of divs are not set to specific dimensions

For a code snippet, you can visit this link: here The html: <html lang="en"> <head> <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet"> <link href="https://ma ...

What methods can I use to obtain negative numbers through swipe detection?

In my code, I am using three variables. The first one is x which serves as the starting point, followed by myCount which counts the number of swipes a user performs, and finally, dist which calculates the distance from the initial point. I want to set myC ...

Automatically adjust multiple images on an HTML webpage

Just starting out with html programming here. Looking to add top margin using a span class, any tips on how to tackle this issue? ...

Exploring how to extract table data using XPath in PHP through continuous loops

Here is an example of the HTML code for a table: <tbody> <tr>..</tr> <tr> <td class="tbl_black_n_1">1</td> <td class="tbl_black_n_1" nowrap="" align="center">23/07/14 08:10</td> <td ...

Reset the button is behaving in the same way as the submit button

I'm having an issue with the script below where the reset button is acting like a submit button as well. Can anyone help me troubleshoot this problem? Thank you. HTML <input type="image" name="submit" value=" " src="image.png"> <input t ...

Tips for correctly center aligning a Div element

I'm facing some challenges with properly centering my website It appears to be centered when I zoom out. However, for users who don't zoom out, it looks misplaced. Do you have any suggestions? The site was built using all AP divs and even with a ...

Ways to eliminate spacing from a bullet point in a list?

Is there a way to eliminate indentation from ul? I attempted adjusting margin, padding, and text-indent to 0, but with no success. It appears that setting text-indent to a negative value works - but is this the only solution for removing the indentation? ...

When you click, a new webpage opens within my website, similar to the feature on Facebook

When using Facebook on mobile, clicking on a link to a person's website opens the website in front of the Facebook page. However, when users press the X in the top left corner, it deletes the webpage but keeps Facebook open. On my desktop computer, I ...

Switch the orientation of the unordered list from horizontal to vertical in a dynamic way

Perhaps a repeated inquiry, yet I have been unable to discover a solution for this issue... I am dealing with a div element (referred to as master) that I do not have the ability to adjust in terms of width or height. Contained within the master is anoth ...

Exploring the Concept of Nested ViewModels in Knockout.js Version 3.2.0

I have a global view model that is applied to the main div and I also have other view models that I want to apply to nested elements within my main div However, I am encountering an issue: You cannot bind multiple times to the same element. Below is ...

Change the color of the navbar when scrolling using bootstrap and jquery

Using Bootstrap to design a navigation bar, I have two main goals: I want the navbar to change color when the page is scrolled down by 20%, and then revert back to its original color when scrolling back to the top. When the collapse featu ...

Trouble Viewing Image File

I am facing an issue where I cannot upload an image file from my computer onto my HTML file, as it is not showing up in the browser. However, when I link an image file from the web, it works perfectly fine. I have double-checked the file path and ensured ...

Instructions on separating an array into two table rows "<tr>" with a single foreach loop on the template side

Given the constraints of my working environment, I must divide this array into two separate table rows - one containing half of the data and the other with the remaining half. The array is already sorted in the order that I require: Array ( [product] ...

Executing a jQuery event after a div's background-image has finished rendering

Greetings and thank you for sparing a moment. I'm curious to know if there exists a method through jQuery to execute a function immediately after a background image in a div has completed downloading and rendering. Imagine you have the following div ...