The JavaScript switch statement is malfunctioning

I am facing an issue with a switch statement in my code. The switch has multiple cases that compare values and assign a corresponding text to a variable. However, when I run the switch statement, it always executes the default case even though my condition is true. Why could this be happening?

Value:

Apartment

Code snippet:

var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case (rental_cat == "Apartment"): 
    rental_type='daily';
    alert(rental_type);
    break;
case (rental_cat == "Office"):
    rental_type='work_daily';
    alert(rental_type);
    break;
default:
    rental_type='other';
    alert(rental_type);
    break;
}

Upon execution of the switch statement, the result always shows "other" as the output.

Answer №1

Eliminate the if statement inside the "case" block.

Give this a shot:

var rental_cat = $('#rentals_type').val();

    alert(rental_cat);

    var rental_type = "";

    switch (rental_cat) {

    case "Apartment": 
                                        rental_type='daily';
                                        alert(rental_type);
                                        break;

    case "Office":
                                        rental_type='work_daily';
                                        alert(rental_type);
                                        break;

    default:
                                        rental_type='other';
                                        alert(rental_type);
                                        break;
}

Answer №2

When using a switch statement with the variable rental_cat, it is important to note that you should not include a condition within the case statement. Instead, the comparison is made between the switch and the cases themselves. For example:

This code:

switch (rental_cat) {
  case (rental_cat == "Apartment"): 

is essentially equivalent to:

switch (rental_cat) {
  case true: 

which can further be simplified to:

if (rental_cat === true)

To correct this issue, make sure your switch statement looks like this:

switch (rental_cat) {
  case "Apartment":

Answer №3

To efficiently handle this issue, utilizing a map instead of a switch statement is advised:

var rentalTypesByCat = {
    DEFAULT:        "other",

    "Apartment":   "daily",
    "Office":       "work_daily",
}

var rental_cat = $('#rentals_type').val();
console.log("rental_cat:", rental_cat);

var rental_type = rentalTypesByCat[rental_cat] || rentalTypesByCat.DEFAULT;
console.log("rental_type:", rental_type);

If specificity is required (e.g., due to the possible falsy values in mapped data), consider using the following approach:

var rental_type = rentalTypesByCat[rental_cat in rentalTypesByCat? rental_cat: "DEFAULT"];
console.log("rental_type:", rental_type);

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

Utilizing the {{value}} parameter within the JavaScript block of the thinger.io HTML gadget

When creating an HTML widget with JavaScript code on the thinger.io Dashboard, you can easily include data from the "thing" by using {{value}} within HTML tags. However, incorporating this data into a JavaScript block poses a challenge. Example of a Pure ...

The 'classProperties' React component module is currently not enabled

Encountering an error while running my react module 'classProperties' isn't currently enabled (44:11): } 43 | // componentDidUpdate or try this > 44 | onClick = (e) => { | ^ 45 | e.preventDefault(); 4 ...

"Redirecting to an HTML page from the POST method is not supported in the Flask backend and Vanilla JS frontend setup

Utilizing the selected dropdown value from the frontend to perform calculations on the backend, resulting in an HTML page being returned. It's worth noting that no response is needed from the POST method, such as using return jsonify. Currently, I am ...

Is it feasible for Javascript to trigger a callback or signal with Selenium?

Imagine using Selenium on a web page that utilizes an AJAX request to dynamically update content within a specific #content element. The #content element always has exactly five children, each without any classes, ids, or unique identifiers. Periodically, ...

What is the best way to convert and update document fields in MongoDB to GeoJSON format using Java?

I have a collection in mongodb that stores information about airports and I need to perform some Geospatial Queries. One example document from this collection looks like this: { "_id" : ObjectId("528e8134556062edda12ffe6"), " ...

Issue encountered while attempting to delete dynamically added fields

I'm facing an issue where I am adding 3 fields dynamically (2 text fields and 1 remove button). The add button is functioning correctly, but the problem arises with the remove function. Currently, it only removes the remove button itself and not the o ...

Socket connection in Vue not activating

I've been experimenting with incorporating Vue.js and sockets together, but I'm encountering an issue where my Vue application isn't receiving socket events. Despite following online tutorials, the example provided doesn't seem to work ...

Issue encountered while attempting to send an HTML file using express.js

I have been trying to display an HTML file using Express.js with a static __dirname, but the HTML content does not show up after calling localhost/ var express = require('express'); var web = express(); ...

What is causing me to only receive the first element in a JavaScript array that is being passed from Silverlight?

I'm struggling to pass an array of strings from a Silverlight application to a Javascript function. Despite my efforts, I am only able to retrieve the first element of the array instead of the entire array. Here's a simple representation of the i ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

TypeScript maintains the reference and preserves the equality of two objects

Retrieve the last element of an array, make changes to the object that received the value, but inadvertently modify the original last position as well, resulting in both objects being identical. const lunchVisit = plannedVisits[plannedVisits.length ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Greetings Universe in angular.js

Having trouble creating a Hello World page in angular.js. When I try to display {{helloMessage}}, it shows up instead of Hello World. I'm not sure where the issue lies. Within the folder are two files: angular.min.js and HelloWorld.html. In HelloWorl ...

The W3C validator does not recognize any modifications made after jQuery and JavaScript have been applied

My goal is to ensure that my website passes all errors on the W3C Validator. I have encountered a few errors related to the alt text of images. In an attempt to address this issue, I wrote and added the following code to the <head> <script type=" ...

Getting data from components in React: A step-by-step guide

As a newcomer to Reactjs, I find myself working on an existing project where I am attempting to retrieve product reviews using components. However, my console currently displays 0 reviews. How can I resolve this issue? The file in question is "pages/[slug ...

What's preventing access to class property in TypeScript when using asynchronous methods?

Consider the following TypeScript class: class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } thisworks(input) { console.log("I am " + input) ; ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

Having difficulty integrating plugins like Lighthouse into my Cypress project

I need assistance with integrating the cypress automation plugin into my project. I made changes to my index.js file in the plugin folder, but now I am receiving this error: cy.lighthouse() is not a function Here is my index.js file content: const { light ...

Jade: modify the text box input to show = " ..."

I am new to Jade and Html, and I am currently working on creating a form in Jade. The issue I am facing involves a simple text box that looks like this: input(type='text', name='sessionID', value = 'valueID') Whenever I want ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...