The Combo Box Select2 display is not showing correctly

In my web application, I'm dynamically adding new rows to a table using JavaScript.

Each row contains an element where data is loaded from the ViewBag, and I also want to apply the Select2 class to this element.

Here is the current code snippet:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="443721282127307604706a756a746936276a74">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4635232a232532740672687768766b34256876">[email protected]</a>/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>

The JavaScript code for dynamically adding rows is as follows:

var counter = 1;

var dropdownOptions = @Html.Raw(Json.Encode(ViewBag.Item_ID));

$(function () {
  $("#add").click(function () {
    var newRow = $(
       '<tr id="tablerow' +
       counter +
       '" class ="poSet"> ' +
       "<td>" +
       '<label id="CountItems"><strong>' +
       counter +
       "</strong></label>" +
       "</td>" +
       // Rest of the row creation logic
     );
    
    var selectElement = newRow.find("select"); 

    dropdownOptions.forEach(function (option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    newRow.appendTo("#submissionTable");

    selectElement.select2();

    counter++;
    return false;
  });
});

When the rows are added, the view looks like this:

https://i.sstatic.net/6wMUA.png

The width of the data element appears incorrectly on the first row and then corrects itself in subsequent rows.

There is also an issue with the appearance of the Select2 combo box, it seems to be missing the form-control class. How can I resolve these issues?

Answer №1

To ensure that your drop-down menus expand to fill the available width, a simple solution is to include width:100% in the select2 parameters:

selectElement.select2({width:"100%"});

There are alternative methods such as utilizing the style attribute, but personally, the above approach is the most straightforward and consistent.

If your appears like a regular select, it may not have been applied correctly - the CSS may not have loaded properly (e.g., incorrect/blocked path) or there could be CSS conflicts if another library (e.g., Bootstrap) is in use, requiring additional CSS adjustments or plugins; depending on the specific issue, there should still be some visible change.

Keep in mind that may require extra parameters if it's within a dialog box (impacts the drop-down itself) - although this doesn't seem to be the case here, it's worth mentioning.

In the provided code snippet below, everything appears to be functioning as intended.

Revised code snippet:

var counter = 1;

var dropdownOptions = [{ Value:'1', Text:'one' }, { Value:'2', Text:'two' }];

$(function () {
  $("#add").click(function () {
    var newRow = $(
       '<tr id="tablerow' +
       counter +
       '" class ="poSet"> ' +
       "<td>" +
       '<label id="CountItems"><strong>' +
       counter +
       "</strong></label>" +
       "</td>" +
       '<td width="40%">' +
       '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
       counter +
       ']" id="ItemId[' + counter + ']" required="required" ' +
       "</select>" +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control Qty" name="Qty[' +
       counter +
       ']" value="1" id="Qty[' + counter + ']" onchange="calQtyBase(this)" data-QtyId= ' + counter + ' required="required" />' +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control" name="MeasureBy[' +
       counter +
       ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
       counter +
       ']" value="0.00" id="UnitPrice[' + counter + ']"  onchange="priceBase(this)" data-PriceId= ' + counter + '  required="required" />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control LineTotal" name="Line_Total[' +
       counter +
       ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
       "</td>" +
       "<td>" +
       '<button type="button" class="btn btn-danger" onclick="removeTr(' +
       counter +
       ');">x</button>' +
       "</td>" +
       "</tr>"
     );
    
    var selectElement = newRow.find("select"); 

    dropdownOptions.forEach(function (option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    newRow.appendTo("#submissionTable");

    selectElement.select2({width:"100%"});

    counter++;
    return false;
  });
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c5d3dad3d5c284f682988798869bc4d59886">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e389929686919aa3d0cdd5cdd7">[email protected]</a>/dist/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1360767f7670672153273d223d233e61703d23">[email protected]</a>/dist/js/select2.min.js"></script>


<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</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

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...

What is the best way to access all of the "a" elements contained within this specific div?

Chrome websites are built using the following structure: <div class="divClass"> <a class="aClass"></a> <a class="aClass"></a> <a class="aClass"></a> </div> Utili ...

Customizing the colors of the Input field in the Material UI Text Field component with CSS styling can elevate the overall

import { TextField } from "@mui/material"; import { FunctionComponent } from "react"; interface IProps { type: string; label: string; color: | "error" | "primary" | "secondary" | &quo ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

Converting JavaScript variable values to PHP variables by extracting the content of a textarea

Currently, I'm developing a data filtering mask which triggers when the button <input type="button" /> is clicked. In this process, I have: School classes (1, 2, 3, 4, 5) Sections (A, B, C....Z) Checkboxes for male and female sexes. This ma ...

Exploration of undefined issues in Jquery, Ajax, and JSON parsing

Why am I having trouble accessing field.set_url? http://jsfiddle.net/W4xBJ/ $(document).ready(function(){ $("button").click(function(){ $.getJSON("https://api.deckbrew.com/mtg/cards?color=red&color=blue&rarity=rare&name=fire",function(r ...

How to make a form in PHP that can be saved?

I have put together a straightforward, yet lengthy HTML form and I am in need of a way for users to save their progress on the form and return to it at a later time (security is not a major concern). However, I am struggling with how to save the form' ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

insert the "tr" element directly following the button

I am looking for a way to allow the user to add another input file right next to the button, so they can select and send multiple files at once. https://i.sstatic.net/TI4eJ.png I have tried using various solutions I found during my search but none of the ...

Aligning a large checkbox to the left in Bootstrap 4 styling

Bootstrap 4. <div class="form-group"> <label asp-for="Enabled" class="control-label"></label> <input asp-for="Enabled" class="form-control" type="checkbox" /> <span asp-validation-for="Enabled" class="text-danger"> ...

Organize text documents for website display

Is there a way to code a website that will showcase the 20 most recent text files from a directory, in descending order of newest to oldest, and provide links for viewers to access them on the web? ...

Adjusting the line-height and baseline to accommodate various screen sizes on both mobile and desktop

This problem seems to keep coming back for me. I can't figure out what's causing it. Here are two images showing the issue: On desktops: https://i.sstatic.net/AAGbb.png On mobile devices: https://i.sstatic.net/Zk4pc.jpg As you can see, the ...

Having trouble with the JOSN.parse function not functioning properly

Hello there, I'm currently attempting to extract data from a simple JSON string but encountering an error. The object I am trying to retrieve looks like this: { "heading" : "The movies", "box5" : "Click on icon to add text.", "box1" : "At the movies, ...

Does using .stopImmediatePropagation() in the click event of a menu item have any impact on analytical tools?

Scenario I've implemented a navigation menu that loads subpages into a div using AJAX. While everything seems to be working fine, I noticed a bug where if I navigate to a subpage, then return to the main page and revisit the same subpage, it gets loa ...

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: https://i.sstatic.net/oSAi8.jpg Here is a snapshot of my database: https://i.sstatic.net/j5PpZ.jpg Below is my event controller class: <?php namespace App\Http\Contro ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...

What is the process for making a custom texture map to use in ThreeJS materials?

Recently, I acquired a fbx model that utilizes a UV map to efficiently texture the model. The model is composed of a single mesh that needs to be colored using 4 quadrants as shown in the image below: https://i.sstatic.net/RR6m3.png To achieve this color ...

What is the best way to center a SVG and a span vertically within an inline unordered list?

My <ul> element contains 2 <li> items with styling using display: inline-block. Unfortunately, the SVG and text inside each <li> are not vertically aligned. I attempted to use vertically-align: middle since they're both inline-block ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...