Guide to removing values from an HTML selected list box with a single click

Being a beginner in Jquery, I encountered an issue with deleting values in batches of 3. When I try to remove categories by clicking the "Remove Category" button, it seems to select and delete them one at a time or two at a time instead of removing them in sets of three. This behavior has left me confused. My goal is to have every group of three selected values deleted together from the bottom when the "Remove Category" button is clicked.

var one = $('.select-manage-category').val();
var two = $('.select-manage-category1').val();
var three = $('.select-manage-category2').val();
$('#add-category').click(function() {
  $(
    '.select-manage-category, .select-manage-category1, .select-manage-category2'
  ).each(function() {
    $('#selected-lst-values').append('<option value="' + $(this).val() + '">' + $(this).val() + '</option>');
  });
});
$('#remove-category').click(function() {
  $('.select-manage-category, .select-manage-category1, .select-manage-category2').each(function() {
    var the_index = $(this).val() - 1;
    $('#selected-lst-values')
      .find('option:nth-last-of-type(' + the_index + ')')
      .remove();
  });
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
  width: 100px;
  float: left;
  margin-right: 4px;
}

p {
  clear: left;
  text-align: center;
}

#selected-lst-values {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>

<div><select class="form-control select-manage-category1" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select>
</div>
<p class="text-center color-red">You can add up to 20 categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category">
<input id="remove-category" name="add" type="button" value="Remove Category">
<div><select id="selected-lst-values" class="form-group percent-100" size="5">
</select></div>
<button class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save</strong> 
    <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span>
</button>

Answer №1

Thank you for the detailed explanation. Please take a look at the revised js fiddle

var one = $('.select-manage-category').val();
var two = $('.select-manage-category1').val();
var three = $('.select-manage-category2').val();
$('#add-category').click(function() {

  $('.select-manage-category, .select-manage-category1, .select-manage-category2'
  ).each(function() {
    $('#selected-lst-values').append('<option value="' + $(this).val() + '">' + $(this).val() + '</option>');
  });
});

$('#remove-category').click(function(){
var length=$('#selected-lst-values option').length;
for( var i=0; i<3 ;i++)
{
 $('#selected-lst-values option:eq(' + (length - 1) + ')').remove();
length --;
}
});
.select-manage-category,.select-manage-category1,.select-manage-category2{
width:100px;
float:left;
margin-right:4px;
}
p{clear:left;text-align:center;}

#selected-lst-values{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select>
</div>
<div>
<p class="text-center color-red">You can add up to 20 categories</p></div>
<input id="add-category" name="add" type="button" value="Add Category">
<input id="remove-category" name="add" type="button" value="Remove Category">
<div><select id="selected-lst-values" class="form-group percent-100" size="5">
</select></div>
<button class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save</strong> 
    <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span>
</button>

View updated fiddle here

Answer №2

Hopefully, this JavaScript code will meet your needs. Make sure to replace the existing remove function with the one below:

$('#remove-category').click(function(){
  var index= $('.select-manage-category')[0].selectedIndex || $('.select-manage-category1')[0].selectedIndex || $('.select-manage-category2')[0].selectedIndex;
  $('.select-manage-category option:eq(' + index + ')').remove();
  $('.select-manage-category1 option:eq(' + index + ')').remove();
  $('.select-manage-category2 option:eq(' + index + ')').remove();
});
.select-manage-category,.select-manage-category1,.select-manage-category2{
width:100px;
float:left;
margin-right:4px;
}
p{clear:left;text-align:center;}

#selected-lst-values{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
    <option>1</option>
    <option>2</option>
    <option>1</option>
    <option>2</option>
</select>
</div>
<div>
<p class="text-center color-red">You can add up to 20 categories</p></div>
<input id="add-category" name="add" type="button" value="Add Category">
<input id="remove-category" name="add" type="button" value="Remove Category">
<div><select id="selected-lst-values" class="form-group percent-100" size="5">
</select></div>
<button class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save</strong> 
    <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span>
</button>

Check out the updated fiddle here.

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

The rapid influx of Ajax requests is overwhelming the server's capacity - JQUERY

I understand the issue at hand, but I am struggling to find a solution. Let's consider that I have 4 files - index.php, ajax.php, more-ajax.php, and custom.js. In my index file, there is a <div id="content"></div> element that loads conte ...

Antd 4: Updating the value in Form.List dynamically with setFieldsValue

<Form> <Form.List name="projects"> {fields => ... fields.map(field => <Form.Item name={[field.key, "type"]} hidden={true} initialValue={type} />) ... } </Form.List> </Form> ...

Is jQuery returning null because the selected option is not being posted correctly?

I am having an issue with this jQuery script as it is returning null. I have tried different syntax for selected options, but here is the code that I currently have: The script is functioning correctly and successfully runs, enabling me to download the Ex ...

Tips for adding a personalized background below the jumbotron

#particles-js{ background:rgba(0, 10, 14,.8); height:100%; position: absolute; top:55px; left:0; width:100%; min-height:700px; background-size: cover; background-position: center; overflow: hidden; } #jumbotron{ margin: auto; width ...

Tips for switching between two CSS classes for a single control in ASP.Net

<style type="text/css> .CssStyle1 { font: 10pt Verdana; font-weight:700; color: Green; } .CssStyle2 { font: 15pt Times; font-weight:250; color: Blue; } </style> <as ...

Is it possible to efficiently update the innerHTML of multiple div elements using a single function?

Upon clicking a button, I am dynamically updating the content of multiple divs using innerHTML. Currently, the button triggers a new video source to load, but I also want to change other types of content in different divs at the same time. I wonder if cha ...

The success callback in jQuery's $.ajax function is returning empty data

Using jQuery $.ajax to send a basic contact form to a php script, I am attempting to assess the response. Depending on the result, I aim to either replace the entire form with a "thank you" message or populate an "error" div with any issues encountered. De ...

The three.js element is not appearing as expected on my webpage

Struggling to implement three.js into my HTML project Here's the HTML code for the canvas: https://i.sstatic.net/8uuN7.png And here is the JS code: https://i.sstatic.net/XYpk5.png Unfortunately, I'm encountering an error and the cube isn' ...

`How can one trigger a click event on a react geo chart?`

I'm currently working with a basic geo chart in React Geocharts. <Chart width={calculateMapHeight()} height={'575px'} chartType="GeoChart" data={user.details} getSelection={(e) => console.log('test')} ...

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

"Why does the form.submit() function fail in IE9 when the form is in an iframe and the user is coming from Gmail

I have recently developed a function within my CodeIgniter framework that allows me to send emails with a backlink to my site. The link directs users to a page on my website that includes an iframe. Within this iframe, I have implemented a file input form ...

The scrollBy function is disabled when the user is already scrolling (iOS only)

I am facing an issue with a list of items that gets a new item added to it at regular intervals, resembling a data feed. The list is supposed to update in real-time as new items come in, but if the user scrolls down, it should stay in place to enhance read ...

Prevent accidental activation of links with touchend event

Currently, I am utilizing the touchend event to prevent iOS from requiring two touches to activate href links. Although this method is effective, it is causing the links to be triggered accidentally while scrolling. I am aware that the ideal solution invo ...

What is the process for retrieving the search function value in Node Js?

I have been working on creating a search bar functionality using the Express Framework in Node.JS, Handlebars, and MySQL. The connection to MySQL is all set up and functioning properly, I have installed body parser, and even tested the query directly in ph ...

Is it recommended to employ a switch statement in order to link CSS IDs with JavaScript variables?

function getVariableFromID(ID) { switch (ID) { case "GTA1": return GTA1; case "GTA2": return GTA2; case "GTA3": return GTA3; ... case "GTJ0": return GTJ0; } } In my code, I have implement ...

Search two arrays in a loop and identify variations with a unique approach

Currently, I am facing a challenge that I need assistance with. I am working on an updater that retrieves an XML list of files from a CDN and compares it with an older list to identify any file differences. The objective is to determine which files are out ...

Dynamically load an external JavaScript file based on the presence or absence of specific elements on the webpage

Hi there, I have a question for you all. Situation: We are using a javascript tool to conduct A/B testing on our landing page designs. I want version A (control) to be linked to one external javascript file, while version B (variation) is linked to a diff ...

Is there a way to remove a specific row from both an HTML table and a MySQL database using CodeIgniter?

Just diving into CodeIgniter and successfully retrieved data from MySQL to display in an HTML table. Now, the challenge is to delete specific rows in MySQL. Imagine a scenario where there are 10 rows in the table, each accompanied by a checkbox, and a Del ...

Organizing an angular expansion panel

I am currently dealing with an expansion panel that has a lot of content. The layout is quite messy and chaotic, as seen here: https://ibb.co/Y3z9gdf It doesn't look very appealing, so I'm wondering if there is a way to organize it better or ma ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...