Utilizing a drop-down selection menu and a designated container to store chosen preferences

My form includes a select dropdown that displays available options (populated from a PHP database). Users can choose options from the list, which are then added to a box below to show all selected items. However, I am facing a challenge with the multiple select box.

Here is how it appears: https://i.sstatic.net/dL30m.png

When an item is selected and the + Add button is clicked, the item is removed from the list and placed in the multiple select box. Subsequently, if a single item is selected from the box and the - Remove button is clicked, it goes back to the select dropdown.

After submitting the form, I aim to save all items in the box in an array. The only way I have discovered to achieve this is by selecting the items when they are added to the multiple select box, causing them to appear highlighted. If a user clicks on any items within the box, they will be deselected and not saved in the array upon submitting the form.

This poses an issue because the - Remove button allows a single selected option to be returned to the dropdown select, where it is sorted alphabetically. This functionality does not work when multiple items are selected.

Below is the code snippet:

$("#agregarFamilia").click(function() {
  if ($('#idFamilia').val() > 0) {
    var names = $('#idFamilia').find('option:selected').text();
    var newOption = $('<option></option>').attr("selected", "selected");
    newOption.val(names);
    newOption.html(names);
    $("#nombresFamilia").append(newOption);
    $("#idFamilia option:selected").remove();
  }
});

$("#removerFamilia").click(function() {
  var length = $('#idFamilia').children('option').length;
  var names = $('#nombresFamilia').find('option:selected').text();
  $("#nombresFamilia option:selected").remove();
  $("#idFamilia").append($("<option></option>").val(length + 1).html(names));

  //Returns the removed item to the dropdown list in alphabetical position
  var foption = $('#idFamilia option:first');
  var soptions = $('#idFamilia option:not(:first)').sort(function(a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
  });
  $('#idFamilia').html(soptions).prepend(foption);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="form-group">
  <div class="col-md-6">
    <select id="idFamilia" name="idFamilia" class="form-control">
      <option value="0">Select</option>
      <option value="1">PCR</option>
      <option value="2">CABLES</option>

    </select>
  </div>

  <div class="col-md-2">
    <a style="display:block;width:145px" id="agregarFamilia" class="btn btn-primary">
      <span class="fa fa-plus"></span> Add
    </a>
  </div>
</div>

<div class="form-group">
  <label for="nombresFamilia" class="col-md-4 control-label"></label>
  <div class="col-md-6">
    <select multiple="multiple" id="nombresFamilia" name="nombresFamilia[]" class="form-control">
    </select>
  </div>

  <div class="col-md-2">
    <a style="display:block;width:145px" id="removerFamilia" class="btn btn-danger">
      <i class="fa fa-minus"></i> Remove selection
    </a>
  </div>
</div>

I'm exploring more efficient ways to implement this rather than using the multiple select box. Although checkboxes were suggested as an alternative, I must adhere to this design.

Answer №1

My suggestion would be to rethink the approach of having selected items as a form element. Instead, consider converting them into an unordered list (ul) that is dynamically created or modified based on the selection from the first select list. This way, you can use a hidden input field to store the selected items and pass them along with the rest of the form data.

Each line item in the list now features a delete button for easy removal. Event delegation is necessary for handling the click event on these dynamically added buttons within the DOM.

$("#agregarFamilia").click(function() {
  if ($('#idFamilia').val() > 0) {
    var names = $('#idFamilia').find('option:selected').text();
    var newOption = $('<option></option>').attr("selected", "selected");
    newOption.val(names);
    newOption.html(names);
    $("#nombresFamilia").append(newOption);
    $("#idFamilia option:selected").remove();
    $('#selectedList').append('<li>'+names+'<button type="button" class="delete btn btn-danger btn-xs pull-right">Remove</button></li>')
  }
});

$("body").on("click",".delete", function() {
  var name = $(this).parent().text().replace(/Remove/,'');
  $(this).parent().remove();
  $("#idFamilia").append($("<option></option>").val(length + 1).html(name));

  //Returns the removed item to the dropdown list in alphabetical position
  var foption = $('#idFamilia option:first');
  var soptions = $('#idFamilia option:not(:first)').sort(function(a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
  });
  $('#idFamilia').html(soptions).prepend(foption);
});
#selectedList li {margin-bottom:10px}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="form-group">
  <div class="col-md-6">
    <select id="idFamilia" name="idFamilia" class="form-control">
      <option value="0">Select</option>
      <option value="1">PCR</option>
      <option value="2">CABLES</option>

    </select>
  </div>

  <div class="col-md-2">
    <a style="display:block;width:145px" id="agregarFamilia" class="btn btn-primary">
      <span class="fa fa-plus"></span> Add
    </a>
  </div>
</div>

<div>

<ul id="selectedList"></ul>
</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

What are the problems with Internet Explorer in Selenium WebDriver?

Currently dealing with a mouse-over issue in IE while using webdriver code. The functionality works smoothly in Chrome and Firefox, however, the problem arises only in IE. How can I resolve this? Initially focusing on an element and then clicking on a li ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

The background fade effect is not fully displaying in Internet Explorer

My code is designed to create a fade effect on the background while displaying a popup. Here is the div container: This is the CSS used for the same: #VbackgroundPopup{ display:none; position:fixed; _position:absolute; /* hack for internet explorer 6*/ t ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

How do I submit an array of objects in Laravel?

I am currently working with a dynamic table that allows users to add and delete rows. Each row contains input fields where users can enter data for an object. At the moment, I am manually assigning index numbers to the name attribute like this: <input ...

Is there a way to lead to a password-protected page without making it accessible through the URL?

I'm currently honing my skills in web development and embarking on a project to create an interactive puzzle website. The premise is simple - the homepage will feature just an answer input field where users can enter the correct solution to progress t ...

What is the best way to utilize the $('input').on('change', function() method within AngularJS?

I am working on creating a registration form page using AngularJS and I need to display the percentage completed. The form consists of over 50 fields, so I am looking for a simple way to implement this functionality. Below is a snippet of the code I have ...

Tips for creating a JSON array for an AJAX post

const myObject = { subjects: [{ area: "Math"}, {area: "English"}] } $.ajax({ type: 'POST', data: {"mydata": JSON.stringify(myObject)}, url: '/tosubjects', dataType: "json", contentType: "application/json", processData: fals ...

Detect IE 9 and IE 10 with jQuery

My jQuery code works well in Chrome and Mozilla but not in IE. if ($("html").hasClass("ie")) { $(function(){ $('.green-column, .red-column, .grey-column').click(function() { alert($(this).attr("data-type")); ...

CSS: A guide to creating layouts

I wrote this code snippet to display a table: <div class="topologyBalloon" id="bl_c2f03b99-6d62-43c4-9a35-4b4cbf22a7db"> <a href="#close" class="closeTopologyBalloon">×</a> <div class="contentBody"> <table class="deta ...

Deactivate the other RadioButtons within an Asp.net RadioButtonList when one of them is chosen

Is there a way to disable other asp.net radio buttons when one of them is selected? I have three radio buttons, and I want to disable the other two when one is selected. After doing some research, I managed to disable the other two when the third one is se ...

Unforeseen rotation happening in CSS animation

I find myself struggling with my math skills from junior high. My goal is to rotate two divs around the Y axis in opposite directions. I have set up two animations for this purpose: @-webkit-keyframes first{ 0% { -webkit-transform: rotateY(0); } ...

Confirm the dimensions of an image prior to uploading using Node, Express, and Multer

Currently, I am developing a project using Nodejs with the express framework and ejs as the view engine. I have encountered an issue while working on image uploads. I am utilizing Multer for this task, but I need to implement a requirement where images wil ...

Tips for resolving vertical alignment styling for images of varying sizes within Vue.js transition-group?

I have created an image slider example, but I'm facing a styling issue when using images of different dimensions. The element leaving the array is positioned absolutely for smooth transitions, but this causes the image to move up. I am trying to vert ...

The jquery datepicker consistently returns the current date when using PHP $_POST

Just to let you know, I am using the latest version of Codeigniter and Jquery in my project. As a beginner in web programming, I appreciate your patience with me :D This is the view/html code I have: Tanggal Lahir : <input type="text" id="datepicker" ...

Leveraging the withWidth higher order component (HOC) provided by

I am currently using version 3.9.2 of Material UI and experimenting with the withWidth HOC in a server-side rendered application. When I disable Javascript in the debugger options of Chrome Developer Tools, everything functions as expected by displaying t ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

Trouble with selecting a color from the picker tool

Working with HTML markup often presents challenges, especially when it comes to using a color picker on Mac OS. I find that trying to match the exact background color of a div element by picking up color from an image can be tricky. After using the Mac co ...

Encountering a deployment issue on Vercel while building with NextJS

I'm facing issues while attempting to deploy my Nextjs app on Vercel: Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: (0 , react_development_.useState) is not a function or its ret ...

What is the best way to choose the page number using numeric paging in RadGrid?

I have implemented a JavaScript function that binds onchange to onbeforeunload or a confirm box only when there are changes on the grid. My goal is to target the footer paging anchors in order to prevent triggering the confirm or onbeforeunload events. Us ...