Adjust the appearance of an element based on user selection from a dropdown menu under certain circumstances

I am working on creating a dropdown menu using a JavaScript array. My goal is to display a specific span element when certain options are selected.

For instance, I want the span to be shown only when options "a" and "c" are selected, but not when option "b" is chosen.

var city = ["a","b","c"];

// Populate city dropdown
var select_city = document.getElementById("city");

for(var i = 0; i < city.length; i++) {
    let opt = city[i];
    let el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select_city.appendChild(el);
};

// Show output
var output = document.getElementById("output");

select_city.onchange = function() {
    output.style.display = (this.value == city.value && this.value == !"b") ? "block":"none";
};
#output {
    display: none;
}
<select name="city" id="city">
    <option value="-">- Choose city -</option>
</select>

<span id="output"></span>

Why isn't this code functioning as intended? What adjustments should I make for it to work properly?

Answer №1

The logic for this comparison seems a bit flawed:

this.value == city.value && this.value == !"b"

Since city is an array, there is no direct city.value. It would be more accurate to check if the array includes the value of this.value:

city.includes(this.value)

Moreover, using !"b" doesn't convey a clear meaning. To verify if something is not equal to a certain value, it's better to use the != (or !==) operator:

this.value != "b"

Therefore, the revised logic should be:

city.includes(this.value) && this.value != "b"

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

Retrieve the number of models from an ajax response that is returning a partial view

I am using ajax to call a method called Issues in the Issues controller. var url = "@(Url.Action("Issues", "Issues"))"; $.ajax({ type: 'POST', url: url, data: issue, dataType: "html", success: function (evt) { $(&apos ...

Updating values in mongoDB using Express.js and axios: A step-by-step guide

I need help figuring out how to update a specific post's data in my mongoDB using its object id. I have created an HTML form that displays the selected post's data and allows me to make changes, then submit the updated data to http://localhost:50 ...

Is there a way to configure my datepicker so that it displays only dates that are later than a specified date

At the heart of my inquiry lies a dilemma: I have two date pickers, one for leave_start and the other for leave_end. If an individual selects "YES" for a future text_field, I aim to ensure that the date pickers only display dates after the person's an ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

Tips for positioning an image in the TOP Right corner below the navbar using CSS

I am currently in the process of learning HTML and CSS, and I would like to practice and conduct research whenever I encounter difficulties. Recently, I have been attempting to style my landing page based on a screenshot that I took. However, I have been u ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

Managing Numerous Ajax Calls

Dealing with Multiple Ajax Requests I have implemented several Like Buttons on a single PHP Page, which trigger the same Ajax function when clicked to update the corresponding text from Like to Unlike. The current code works well for individual Like Butt ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Placeholder fails to appear

After implementing some jQuery validation, I wanted to display a text as a placeholder when the user skipped out of an input field without entering anything. This is the code I wrote: $('input[type="text"]').on('blur', function() { ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Upon selecting a checkbox, I desire for a corresponding checkbox to also be marked

I am looking to enhance my current project by incorporating a feature that allows the user to simply check a checkbox with specific content once. For example, I have a recipes page where users can select ingredients they need for each recipe while planning ...

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful: TypeError: Cannot read property '1' of null This is the module I am working with: var app ...

Concealing a navigation tab with Angular4 in Typescript: A tutorial

I have successfully implemented 3 tabs in my Angular 4 project. At the moment, I am focusing on working with the first two tabs and planning to tackle the third tab in the near future. To keep things clean and organized, I am looking to use JavaScript/Typ ...

JSON and autocomplete feature causing performance problems

Developing an application that functions both online and offline using technologies like application cache and local storage is my current project. Utilizing jQuery mobile along with a jqm autocomplete solution from , I aim to create a seamless user experi ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...

Searching for an attribute with no value in an HTML tag using Selenium: A step-by-step guide

Example: Radio - selected <input id="rdo" type="radio" name="nrdo" value="1" checked> Example: Radio - not selected <input id="rdo" type="radio" name="nrdo" value="1"> Searching for attributes without values in HTML tags using Selenium. ...

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...