Compare two values with jquery

Asked

Viewed 1,086 times

1

Like I do to compare two variables. I have a variable that brings the neighborhood id, called bairrocadastrado, it returns the neighborhood ID equal 1093. Soon I have a foreach that returns all the neighborhoods registered in the system, type bairro_id 995, 1093 etc. Only that the problem is as follows. It finds the ID. It makes the comparison, but always returns the neighborhoods that are not equal, ie the second IF, and are equal. What could be wrong?

  function areasAtendimento()
  {
    // inicia as variaveis
    var id_atendimento = "";
    var id_bairro = "";
    var nomebairro = "";
    var nomecidade = "";
    var nomeestado = "";
    var valorfrete = "";
    var parseResult = "";
    var cidadecadastrada = "";
    var bairrocadastrado = "";
    var resultBairro = "";

    // pegar os itens do session storage
    var getEnderecoLogado = sessionStorage.getItem("dadosendereco");

    $.ajax({
      url: urlBase + "areaatendimento",
      method: 'GET',
      success: function (retorno)
      {

        parseResult = JSON.parse(getEnderecoLogado);
        bairrocadastrado = parseResult[parseResult.length-1].bairroendereco;

        retorno.data.forEach(function (item)
        {
          id_atendimento = item.area_atendimento_id;
          id_bairro = item.bairro.bairro_id;
          nomecidade = item.bairro.municipio.nome;
          nomebairro = item.bairro.nome;
          nomeestado = item.bairro.municipio.estado.nome;
          valorfrete = item.valor_frete;
          valorfrete = valorfrete.replace('.', ',');
          // bairro igual ao que está cadastrado
          if (id_bairro == bairrocadastrado)
          {
            $('.entregatotal').html("R$" + valorfrete);
            $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'block');
          }
          // bairro diferete, não exibe o botão
          if (id_bairro != bairrocadastrado)
          {
            $('.entregatotal').html("R$ 0,00");
            $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'none');
            $('.nao-atendido').css('display','block');
          }
        })
      },
      error: function (XMLHttpRequest, textStatus, errorThrown)
      {
        console.log('Erro');
      }
    });
  }
  • 1

    Javascript operators need to be more specific for ifs, use exactly the same '==' and '!=='

  • What gives console.log(typeof id_bairro, id_bairro, typeof bairrocadastrado, bairrocadastrado);?

  • Felipe, did you see my question ? if you don’t know use the console make Alert 1 to 1 and answer here what gives you.

  • Yes, the problem is that it returns all the registered neighborhood ids and at the time of comparing makes the two ifs. Compare what exists and then the ones that don’t exist saying it’s different. More details in the footer here of the discussion.

  • Which of the variables is an array?

  • bairrocadastrado is a sessionstorage array that takes the id of the neighborhood registered by the client that is 10813. Logo id_neighborhood are all registered neighborhoods that come within ajax, ie within the foreach. In this variable also comes the id of the neighborhood 10813

  • And you want to know ifid_bairro exists in bairrocadastrado, right? What is the structure of bairrocadastrado? Is an array of strings/numbers?

  • registered neighborhood comes from this sessionStorage being as number: Takes the last of the array [{"idcliente":"ecca2c6b-cd15-443b-b4db-5a15d39196c5","cliente_endereco_id":"69b8626d-c8d0-44a0-933a-e38e1a2737cd","cependereco":"89400000","logradouroendereco":"Rua Jaime Correia Pereira","numeroendereco":"90","complementoendereco":"Casa","referencia":"Centro Comunitário","estadoendereco":"Santa Catarina","cidadeendereco":"Porto União","bairroendereco":10813}]

  • Ok, and in that array the value you want to compare is bairroendereco? is to check whether id_bairro is equal to "bairroendereco":10813?

  • yes that’s right. Only I got into the loop and it does not come out of it. It takes all who are and those who do not and compares.kkk

  • Felipe, usa @ before the name for me to receive a notification, otherwise it will be hours before you see your comment :) Okay, then one last question: this array bairrocadastrado may have more than one object inside? or always comes with 1 object inside the array?

  • @Sergio, only 1 object the neighborhood id

  • @Felipemichaeldafonseca ok, it would be case then you have bairrocadastrado = parseResult[parseResult.length-1].bairroendereco[0].bairroendereco? It’s quite long but it seems to me the minimum change to do in the code.

  • yes @Sergio, but that would solve the IF problem?

  • Yes, if is right. The problem is the variable bairrocadastrado not getting what you expected. If bairrocadastrado is right the if will work. You could have if (id_bairro == bairrocadastrado) and below else in time of if (id_bairro != bairrocadastrado). It was a little better for reading the code, but it’s not wrong and the problem is not the != == in this case.

  • sorry @Sergio, but returns the following error: Cannot read Property 'bairroendereco' of Undefined

  • Okay, going back a step. Put here the value of console.log(typeof getEnderecoLogado, getEnderecoLogado); without JSON.parse, right after var getEnderecoLogado =.

  • actually @Sergio if it works only I wanted it to show if the shipping of the bairroendereco is equal to the foreach id. But then he returns all those who are different too, because he is different understood? I believe the error is there, we just do not know how to make it return the correct values and to stop it in the first if it is equal and do not execute the second.

  • @Sergio he returns: string [{"idcliente":"ecca2c6b-cd15-443b-b4db-5a15d39196c5","cliente_endereco_id":"69b8626d-c8d0-44a0-933a-e38e1a2737cd","cependereco":"89400000","logradouroendereco":"Rua Jaime Correia Pereira","numeroendereco":"90","complementoendereco":"Casa","referencia":"Centro Comunitário","estadoendereco":"Santa Catarina","cidadeendereco":"Porto União","bairroendereco":10813}]

  • As for what comes from getEnderecoLogado the correct way is bairrocadastrado = parseResult[0].bairroendereco;, since it is only 1. In relation to "it returns all that are different too" and "we do not know how to make it return the correct values" I still don’t understand what you mean. Refer to retorno ajax or sessionStorage?

Show 15 more comments

2 answers

1

The second IF is replacing the first. Try changing to a ELSE or ELSE IF, like this:

// bairro igual ao que está cadastrado
      if (id_bairro == bairrocadastrado)
      {
        $('.entregatotal').html("R$" + valorfrete);
        $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'block');
      } 
      else if (id_bairro != bairrocadastrado)
      {
        $('.entregatotal').html("R$ 0,00");
        $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'none');
        $('.nao-atendido').css('display','block');
      }

inserir a descrição da imagem aqui

  • "The second IF is replacing the first" ? What do you mean? You can give an example how this can happen?

  • What he said makes sense, because first, he sees 'if neighborhood equal' and then he has run 'if different neighborhood' within the same loop, the second if will be the one that will be run last, it may be that even fill wrong.

  • He always makes the second IF. That is, he finds everyone and if it is different as he finds everyone who they are, he already makes the second. The case is that you are finding all the same and all the different. But I wanted only the same.

  • You have the same class for both Ifs, so if he enters the first and then the second.. The second will prevail, you putting the ELSE or ELSE IF, it will get into one or the other...

  • How would you handle it then? Have any suggestions?

  • @Felipemichaeldafonseca , you have nothing telling the loop to stop the time you find the same, or you use an Else indicating exception, or tell the loop to stop the time you find the same. a Return 0 is enough

  • I don’t understand. Could you explain me? I’m a beginner in Javascript and jquery

  • I tried with Return false and came up with nothing in this situation. It would not be better to make an accountant?

  • @Felipemichaeldafonseca puts the name of the different classes, as if to create two div even, maybe already solved... Type $('.total delivery'). html("R$" + value); and in ELSE $('.total deliveryNaoCad'). html("R$" + value);... But change from the other fields tbm.. And then you deal with show(show) or Hidden(hide) you want to display... I think it would be easier

  • No valid numbers in format String or Number which give the same result in != and ==. Hence my -1.

Show 5 more comments

-1

Try to modify this part:

if (id_bairro === bairrocadastrado)
{
    $('.entregatotal').html("R$" + valorfrete);
    $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'block');
    return false;
} else
{
    $('.entregatotal').html("R$ 0,00");
    $('.bt-finalizar-01 .finalizar-compra-carrinho').css('display', 'none');
    $('.nao-atendido').css('display','block');
}
  • I tried everything they said and it came to nothing.kkkk. So easy thing giving a headache

  • Give a var_dump in 'return' before coming to JS, Upa in Pastebin and send the link, ta strange that kk

  • It’s in the top answer...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.