Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options.

Below is an excerpt from my form: These are just the initial four out of the total 8 selects that need to be ranked

  <label>Spirituality</label>\
 <select id="ranks1" class="form-control form-input" name="answer[]" required>
    <option value="" selected>--</option>
    <?php for ($i=1;$i<=10;$i++){?>
    <option value="<?=$i;?>"><?= $i;?></option>
    <?php } ?>
  </select>
   <label>School</label>
  <select id="ranks1" class="form-control form-input" name="answer[]" required>
    <option value="" selected>--</option>
    <?php for ($i=1;$i<=10;$i++){?>
    <option value="<?=$i;?>"><?= $i;?></option>
    <?php } ?>
  </select>
   <label>Family</label>
  <select id="ranks1" class="form-control form-input" name="answer[]" required>
    <option value="" selected>--</option>
    <?php for ($i=1;$i<=10;$i++){?>
    <option value="<?=$i;?>"><?= $i;?></option>
    <?php } ?>
  </select>
   <label>Friends</label>
  <select id="ranks1" class="form-control form-input" name="answer[]" required>
    <option value="" selected>--</option>
    <?php for ($i=1;$i<=10;$i++){?>
    <option value="<?=$i;?>"><?= $i;?></option>
    <?php } ?>
  </select>

This snippet shows the progress I've made with my script so far:

$(document).ready(function () {
    $("#ranks1").click(function () {
        $('#ranks1 option').prop('disabled', true);
    });
});

I have also added CSS styles specifically for disabled options:

select option[disabled] {
    display: none !important;
}

For more context on how the form appears, you can view it here.

Answer №1

If you're looking to capture the change event instead of the click event, here's an example that demonstrates how to disable the selected option when the change event occurs.

Take a look at the code snippet below:

HTML:

<select id="selectlist">
  <option value="0">Please select</option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

Javascript:

$('#selectlist').on('change', function() {
    var selectedVal = $(this).find(":selected").val();
  if (selectedVal != 0) {
    // Disable the selected value
    var selectedOption = $(this).find('option[value=' + selectedVal + ']');
    selectedOption.attr('disabled', 'disabled');
  }
});

Feel free to check out the JSFiddle link for a live demo: https://jsfiddle.net/tp9urjkb/

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

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

Dealing with two AJAX posts on a single PHP page, where both posts are being sent to the same page without specifying a URL

Managing 2 posts on the same page to execute 2 different PHP scripts is my current challenge. Upon successful validation of all field data in the first POST, a new block will be activated. Within this new block, additional inputs will be displayed. Once t ...

Dynamic elements create an interactive horizontal scrolling experience

I have square elements that will be displayed in a row on the screen extension. These elements are generated dynamically, starting with 2 and going up to 50. Depending on the screen size and number of elements, there may be overflow. In such cases, I want ...

directive still running despite attempting to stop the service

In my modal window, there is a directive that utilizes a service to make HTTP requests at regular intervals using $interval. However, even after closing the modal window, the service continues to run and make requests every 30 seconds. Is there a way to ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

running into an issue while attempting to utilize socket.io

Currently, I am utilising the socket.io swift client on my Iphone SE. Below is the swift code snippet: let socket = SocketIOClient(socketURL: URL(string: "http://example.com:4000")!, config: [.log(true), .forcePolling(true)]); socket.connect(); ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Building an npm module locally: A step-by-step guide

Imagine I'm in the process of working on an application called MyApp and I want to create an NPM module for it, named MyModule. Currently, I can think of two approaches to developing it: Make changes -> save -> npm install /path/to/module in M ...

Tips for maintaining the responsiveness of both images and text within a div container

I'm completely new to HTML and CSS. Everything looked perfectly aligned until I added text inside the three divs and now my images are unbalanced, even though I've set the same width and height: Here is the code snippet: #wrapper{ display:fl ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Overlap between sidebar and navbar

I am currently working on developing an admin panel for one of my projects. I designed a sidebar and implemented a standard bootstrap 4 navbar. However, I encountered a minor issue where the bootstrap 4 navbar is extending to the full width of the page ins ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...

Using a ThreeJS bitmap texture to extrude a shape created with THREE.Shape

I have successfully created a cube with rounded corners using the THREE.Shape object: var shape = new THREE.Shape(); x = width/2; y = height/2; shape.moveTo(x - radius, y); //*** Top right x = -width/2; y = height/2; shape.lineTo(x + radius, y); if (tr) ...

What methods can be used to incorporate jQuery fadeIn and fadeOut into mouse event functions?

Currently, I am utilizing jQuery to switch images on mouse events (specifically hover), but I'm facing difficulty in implementing a smooth transition effect using fadeIn and fadeOut for the function below. var sourceIn = function () { ...

Retrieve a div using Jquery Ajax

I am facing an issue with the ajax response. The .php file I have generates a table <div class="result"> <tr class="distr"> <td><input name="somename" value="value"></input</td> <td> ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

Showing only the objects that are marked as true in the component (React)

I have implemented two key React components. One of them is VideoGameList.js, it serves as an export of an array containing multiple objects. const VideoGameList = [ { id: 1, title: "Fire Emblem Engage", src: vg01, releaseDate: ...