Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
Switch statement only returns the default case

Can someone help me understand, why is my switch case returning the default value. Even when I change all values it only returns the default at first I thought it was a hoisting issue in my code but after debugging it's I found it's the statement, it ignores all other cases. (p.s please don't be mean I just want to understand, the other examples I've seen aren't simply explained and don't have much up votes so I did try.)

var shippingMethod = document.querySelector("[name=r_method]:checked").value;
var shippingChoice;


switch(shippingMethod) {
    case "usps":
        shippingChoice = 2;
        break;
    case "ups":
        shippingChoice = 3;
        break;
    default:
        shippingChoice = 0;
        break;
}
console.log(shippingChoice);

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I would suggest adding an if statement to verify there is a value for shippingMethod. As well, when querying for the value, make sure to include quote ("") around the value of the name.

var shippingMethod = "default";
var shippingChoice;

if (document.querySelector('[name="r_method"]:checked') != null)
{
  shippingMethod = document.querySelector('[name="r_method"]:checked').value;
}

switch(shippingMethod) {
    case "usps":
        shippingChoice = 2;
        break;
    case "ups":
        shippingChoice = 3;
        break;
    default:
        shippingChoice = 0;
        break;
}
console.log(shippingChoice);

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda