Two interdependent select fields

I am currently working on creating two select fields where, upon selecting an option in the first field, some options in the second field should be hidden. I have almost achieved this, but my script is unable to locate certain options in the first select field. When I manually add these options to the first field, it works, but only for that specific option. I require the script to hide options in the second select field based on the selection made in the first field.

The challenge lies in the fact that I am restricted from adding any classes or ids to the elements.

It seems like I may have made a mistake in how I am instructing the script to edit the elements, but I am unsure of an alternative approach.

HTML

<select name="NameOne">
  <option value="First">Lorem Ipsum1</option>
  <option value="Second">Lorem Ipsum2</option>
  <option value="Third">Lorem Ipsum3</option>
  <option value="CD">Dolor2</option>
</select>

<select name="NameTwo">
  <option value="AB">Dolor1</option>
  <option value="CD">Dolor2</option>
  <option value="EF">Dolor3</option>
</select>

JS

$("select").change(function(){
  if($(this).val() == "Second") {
    $('option[value="CD"]', this).addClass('hidden');
  } else {
    $('option[value="CD"]', this).removeClass('hidden');
  }
});

CSS

.hidden {
  display: none
}

Any assistance would be greatly appreciated.

Answer №1

There seems to be an issue with the code snippet below:

$('option[value="CD"]', this)...

To simplify, this targets the option within the currently clicked select element. As you clicked the first select, this refers to the first select and attempts to find an option with the value 'CD', which is not present. The solution? Target the second select, locate the option with the value 'CD', and modify its class.

Give this a try:

// Modify to focus on only the first select as selecting all selects does not make sense.
$("select").change(function(){
//$("select[name='NameOne']").change(function(){ <--- better
  var secondSelect = $("select[name='NameTwo']"); //get second select
  if($(this).val() == "Second") {
    secondSelect.find('option[value="CD"]').addClass('hidden'); //find option with CD and add Class
  } else {
    secondSelect.find('option[value="CD"]').removeClass('hidden');
  }
});
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
  <option value="First">Lorem Ipsum1</option>
  <option value="Second">Lorem Ipsum2</option>
  <option value="Third">Lorem Ipsum3</option>
  <option value="CD">Dolor2</option>
</select>

<select name="NameTwo">
  <option value="AB">Dolor1</option>
  <option value="CD">Dolor2</option>
  <option value="EF">Dolor3</option>
</select>

$("select").change(function(){
 var secondSelect = $(select["name='NameTwo']"); 
 if($(this).val() == "Second") {
    secondSelect.find('option[value="CD"]').addClass('hidden');
  } else {
    secondSelect.find('option[value="CD"]').removeClass('hidden');
  }
});

Answer №2

To achieve the desired outcome, you must modify the query on a specific select element while also manipulating the visibility of the option within another select. This method ensures that only the relevant options in the select are affected by the changes made.

$("select[name='NameOne']").change(function() {
  if ($(this).val() == "Second") {
    $("select[name='NameTwo'] option[value='CD']").addClass('hidden');
  } else {
    $("select[name='NameTwo'] option[value='CD']").removeClass('hidden');
  }
});
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
  <option value="First">Lorem Ipsum1</option>
  <option value="Second">Lorem Ipsum2</option>
  <option value="Third">Lorem Ipsum3</option>
  <option value="CD">Dolor2</option>
</select>

<select name="NameTwo">
  <option value="AB">Dolor1</option>
  <option value="CD">Dolor2</option>
  <option value="EF">Dolor3</option>
</select>

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

In order to prevent JavaScript code from running on pages other than page 1 in DataTable,

Working on my Django project, I have an app that utilizes a DataTable with JQuery. In one of the table columns, there is a link embedded with a JS script. Everything functions properly on the initial page but encounters issues when navigating to subsequen ...

What is the method in jQuery $.ajax to send an array without enclosing it in square brackets?

If a web form contains multiple inputs with the same name, it will be interpreted as an array by a Servlet: Form: <form> User 1:<input name="user" /> User 2:<input name="user" /> User 3:<input name="user" /> <in ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Tips for displaying the Year Dropdown before the Month Dropdown in Jquery Datepicker

Currently utilizing the jQuery UI datepicker. Is there a way to display the Year Dropdown first and the Month Dropdown second in the jQuery Datepicker? I am looking to achieve a layout similar to this: ...

Using JQuery to create a button dynamically through an AJAX request

As someone from Russia, please excuse any shortcomings in my English. Currently, I am utilizing AJAX to load a portion of a webpage. For instance: <script type="text/javascript> $("#link1").click(function(){ $.post("ajax.php", { act: "load" }, ...

Unable to generate webpage source code

Having some trouble with my Next.js project as I'm using getStaticProps and getStaticPath to build a page, but unfortunately, the HTML is not being generated in the page source. This issue is causing problems with SEO, and I haven't implemented r ...

The method provided by the FullScreen API is not effective in cancelling the fullscreen mode

After testing my code in Google Chrome, I encountered the following error message: Uncaught TypeError: Object #<HTMLDivElement> has no method 'webkitCancelFullScreen' Interestingly, I also received a similar error while running the code i ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Inquiries regarding the functionality of passport.js, particularly concerning the user.id implementation

In my model, doc, or record, there is no field labeled as id. So, how is it possible that done(null, user.id) works? I do have an _id but not an id. It seems like a passport object is being added to my session with the _id of the user in the database. But ...

Retrieve information from an HTML table on a website and transfer it to a spreadsheet in Excel

I'm looking for assistance with extracting data from a website using VBA. I have an Excel table with ETF tickers, links, and prices, and I'm attempting to retrieve the previous day's closing price from each link using VBA. The challenge I&ap ...

Automated login feature in JQuery utilizing localStorage

I've been working on implementing an automatic login feature for users using the "Remember Me" functionality. Below is the code I have written, but unfortunately, it's not logging in users automatically: if (localStorage.getItem("username") != ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

Why does this asynchronous function initially return nothing, only to suddenly return all results on subsequent tries?

My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas." This is how I invoke the function: ...

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Tips for preventing an AJAX response from populating a select dropdown

https://i.sstatic.net/gA1VE.gif In the example above, there is a placeholder (an option without value) that says something like Select Subcategory. When I change the category value, the subcategories are displayed. But what I want is for the subcategory ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

Navigating a page without embedding the URL in react-router-dom

In my application, I am utilizing react-router-dom v5 for routing purposes. Occasionally, I come across routes similar to the following: checkup/step-1/:id checkup/step-2/:id checkup/step-3/:id For instance, when I find myself at checkup/step-1/:id, I int ...