Keyword Search Assign If and Else with Javascript

Asked

Viewed 180 times

-2

Hello folks I am trying to make an automated freight selection in my shop, why the integrated shop platform does not offer specific freight option for products, so I have:
Conveyor: Only for T-shirts
Post Office: Masks and Mugs

So I wanted to locate the key words "T-shirt" and "Mascara"; in this way print the message warning the form of shipping that has available, disabling the other;

Facts: I was only able to locate with Document.indexof and IF and Else does not work; /

 
    function inicia() {    

   
   if (true) { 

         var nomeproduto=document.querySelector(".produto-info a").innerHTML
         
         var mask=nomeproduto.indexOf("Mascara");

          if (mask > 0) { 
            var firstfrete=document.querySelector(".formas-envio > ul > li:first-child");

            firstfrete.textContent = "Mascaras & Canecas somente por Correios!";
          } 

          else { alert("Frete Mascaras & Canecas Somente Correios"); }  
           } 

             else { alert("");} 
      
     

  if (true) { 
        
         
         var shirt=nomeproduto.indexOf("Camiseta");

          if (shirt > 0) {  

            var firstfrete=document.querySelector(".formas-envio > ul > li:last-child");

            firstfrete.textContent = "Camisetas exclusivamente Transportadora, Demais produtos apenas correios!";


          } 

          else { alert("Frete Camisetas Somente Transportadora"); }        

           } 

     else { alert("");}  

            }
    window.addEventListener("load",inicia);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/all.min.css?v=42a13fc" type="text/css">
       <link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/bootstrap-responsive.css?v=42a13fc" type="text/css">
      <link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/style-responsive.css?v=42a13fc">
      <link rel="stylesheet" href="https://www.imaginizesw.com.br/tema.css?v=20200613-165443">
      
      
<tbody style="padding: 40px;">
    <tr data-produto-id="45146859" data-produto-quantidade="2">
             
              <td class="sem-borda">
                <div class="produto-info">
                  
                   <a href="https://www.imaginizesw.com.br/camiseta-rick-and-morty-portal-gun-portal-dimensional-rick-and-morty-serie--" class="">
                    <h2>Mascara Rick and Morty Portal Gun - Portal Dimensional - Rick and Morty Serie</h2>
                  </a>                 
                 
<a href="https://www.imaginizesw.com.br/camiseta-rick-and-morty-portal-gun-portal-dimensional-rick-and-morty-serie--" class="">
                    <h2>Camiseta Rick and Morty Portal Gun - Portal Dimensional - Rick and Morty Serie</h2>
                  </a>  


                </div>
              </td>
              

  
    <div class="preco-produto destaque-preco ">
        
        
          
            
              <div>
                <s class="preco-venda titulo" style="font-family: Roboto;">
                  R$ 69,00
                </s>
                <strong class="preco-promocional cor-principal titulo" style="font-family: Roboto;">
                  R$ 59,00
                </strong>
              </div>
            
          
        
      
    </div>
  


                </td>
              
              <td class="clearfix">
                <form action="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar" method="post">
                  <div class="quantidade">
                    <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar/1" class="icon-minus"></a>
                    <input type="text" class="input-mini" name="quantidade" value="2" autocomplete="off" style="font-family: Roboto;">
                    <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar/3" class="icon-plus"></a>
                    <button class="botao principal pequeno atualizar-quantidade" style="background-color: rgb(255, 215, 0); font-family: Roboto;">Atualizar quantidade</button>
                  </div>
                </form>
              </td>
              
                <td>
                  <div class="preco-produto">
                    <strong class="preco-promocional cor-principal titulo" style="font-family: Roboto;">
                      R$ 118,00
                    </strong>
                  </div>
                </td>
              
              <td>
                <div class="excluir">
                  <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/remover" class="icon-trash"></a>
                </div>
              </td>
            </tr>
          

          
            <tr class="hidden-phone bg-dark">
              <td colspan="4">&nbsp;</td>
              
                <td colspan="2">
                  <div class="subtotal">
                    <span>Subtotal: </span>
                    <strong class="titulo cor-principal" data-subtotal-valor="118.0" style="font-family: Roboto;">
                      R$ 118,00
                    </strong>
                  </div>
                </td>
              
            </tr>
          

          
          
              </td>
              <td colspan="2">
 <div class="formas-envio">
                  <ul>
                    <li><label class="radio"><input type="radio" name="formaEnvio" value="195" data-valor="13.93" data-code="transportadora"><b class="prazo">10 dias úteis</b> <span class="cor-principal valor">R$ 13,93</span> <span class="nome">Transportadora</span></label></li><li><label class="radio"><input type="radio" name="formaEnvio" value="59360" data-valor="16.53" data-code="Correios-2"><b class="prazo">15 dias úteis</b> <span class="cor-principal valor">R$ 16,53</span> <span class="nome">Correios - SEDEX</span></label></li></ul>
                  
</div>







 <div id="preco-frete" style="display: block;">
<span class="texto">
Comprando mais <span id="falta">R$ 32.00</span> ganhe <span>FRETE GRÁTIS!!!</span>
</span>
</div></div>
              </td>
            </tr>

           
              </td>
            </tr>
          
        </tbody>

  • What is the purpose of if (true)?

2 answers

0

Function starts() {

const nomeproduto = document.querySelector(".produto-info a").innerHTML

// Como é trata a string como se fosse um array, 
// retorna a posição e -1 caso não encontre
if (nomeproduto.toLowerCase.indexOf("mascara") > -1) { 
    // Caso não funcione, precisa trocar para let,
    // porem acredito que funcione, pois o const só não permite que o objeto seja sobreescrito
    const firstfrete=document.querySelector(".formas-envio > ul > li:first-child");
    firstfrete.textContent = "Mascaras & Canecas somente por Correios!";
} else { 
    console.log("Frete Mascaras & Canecas Somente Correios"); 
}  
// Pelo exemplo, poderia fica no else anterior
if (nomeproduto.toLowerCase.indexOf("camiseta") > -1) { 
    const firstfrete=document.querySelector(".formas-envio > ul > li:last-child");
    firstfrete.textContent = "Camisetas exclusivamente Transportadora, Demais produtos apenas correios!";
} else {
    console.log("Frete Camisetas Somente Transportadora"); 
}

}

window.addeventlistener("load",starts);

function inicia() {    

    const nomeproduto = document.querySelector(".produto-info a").innerHTML
    
    // Como é trata a string como se fosse um array, 
    // retorna a posição e -1 caso não encontre
    if (nomeproduto.toLowerCase.indexOf("mascara") > -1) { 
        // Caso não funcione, precisa trocar para let,
        // porem acredito que funcione, pois o const só não permite que o objeto seja sobreescrito
        const firstfrete=document.querySelector(".formas-envio > ul > li:first-child");
        firstfrete.textContent = "Mascaras & Canecas somente por Correios!";
    } else { 
        console.log("Frete Mascaras & Canecas Somente Correios"); 
    }  
    // Pelo exemplo, poderia fica no else anterior
    if (nomeproduto.toLowerCase.indexOf("camiseta") > -1) { 
        const firstfrete=document.querySelector(".formas-envio > ul > li:last-child");
        firstfrete.textContent = "Camisetas exclusivamente Transportadora, Demais produtos apenas correios!";
    } else {
        console.log("Frete Camisetas Somente Transportadora"); 
    }
}
   
window.addEventListener("load",inicia);

function freteMascara(texto){
    // Como é trata a string como se fosse um array, 
    // retorna a posição e -1 caso não encontre
    if (texto.toLowerCase().indexOf("mascara") > -1) { 
        const mascara=document.querySelector(".formas-envio > ul > li:first-child");
        mascara.textContent = "Mascaras & Canecas somente por Correios!";
    }
}
function freteCamiseta(texto){
    // Como é trata a string como se fosse um array, 
    // retorna a posição e -1 caso não encontre
    if (texto.toLowerCase().indexOf("camiseta") > -1) { 
        const camiseta=document.querySelector(".formas-envio > ul > li:last-child");
        camiseta.textContent = "Camisetas exclusivamente Transportadora, Demais produtos apenas correios!";
    }
}

function inicia() {    
  // Como possui mais de uma tag a na classe produto-info
  // Estava apenas pegando o primeiro
  // Caso tenha sempre um, trocara para o querySelector e tirar o for
    const produtos = document.querySelectorAll(".produto-info a")
    for(const produto of produtos) {
        freteMascara(produto.innerHTML)
        freteCamiseta(produto.innerHTML)
    }
}
   
window.addEventListener("load",inicia);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/all.min.css?v=42a13fc" type="text/css">
       <link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/bootstrap-responsive.css?v=42a13fc" type="text/css">
      <link rel="stylesheet" href="https://cdn.awsli.com.br/production/static/loja/estrutura/v1/css/style-responsive.css?v=42a13fc">
      <link rel="stylesheet" href="https://www.imaginizesw.com.br/tema.css?v=20200613-165443">
      
      
<tbody style="padding: 40px;">
    <tr data-produto-id="45146859" data-produto-quantidade="2">
             
        <td class="sem-borda">
            <div class="produto-info">
                
                <a href="https://www.imaginizesw.com.br/camiseta-rick-and-morty-portal-gun-portal-dimensional-rick-and-morty-serie--" class="">
                    <h2>Mascara Rick and Morty Portal Gun - Portal Dimensional - Rick and Morty Serie</h2>
                </a>                 
                
                <a href="https://www.imaginizesw.com.br/camiseta-rick-and-morty-portal-gun-portal-dimensional-rick-and-morty-serie--" class="">
                    <h2>Camiseta Rick and Morty Portal Gun - Portal Dimensional - Rick and Morty Serie</h2>
                </a>  

            </div>
        </td>

        <!-- TD faltando -->
        <td>
            <div class="preco-produto destaque-preco ">
                <div>
                    <s class="preco-venda titulo" style="font-family: Roboto;">
                        R$ 69,00
                    </s>
                    <strong class="preco-promocional cor-principal titulo" style="font-family: Roboto;">
                        R$ 59,00
                    </strong>
                </div>
            </div>
        </td>
              
        <td class="clearfix">
            <form action="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar" method="post">
                <div class="quantidade">
                    <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar/1" class="icon-minus"></a>
                    <input type="text" class="input-mini" name="quantidade" value="2" autocomplete="off" style="font-family: Roboto;">
                    <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/atualizar/3" class="icon-plus"></a>
                    <button class="botao principal pequeno atualizar-quantidade" style="background-color: rgb(255, 215, 0); font-family: Roboto;">Atualizar quantidade</button>
                </div>
            </form>
        </td>
              
        <td>
            <div class="preco-produto">
            <strong class="preco-promocional cor-principal titulo" style="font-family: Roboto;">
                R$ 118,00
            </strong>
            </div>
        </td>
              
        <td>
            <div class="excluir">
                <a href="https://www.imaginizesw.com.br/carrinho/produto/45146859/remover" class="icon-trash"></a>
            </div>
        </td>
    </tr>
          
    <tr class="hidden-phone bg-dark">
        <td colspan="4">&nbsp;</td>
        <td colspan="2">
            <div class="subtotal">
                <span>Subtotal: </span>
                <strong class="titulo cor-principal" data-subtotal-valor="118.0" style="font-family: Roboto;">
                    R$ 118,00
                </strong>
            </div>
        </td>
    </tr>
     <!-- fechando sobrando           </td>  -->
     <!-- faltando -->
     <tr>
        <td colspan="2">
            <div class="formas-envio">
                <ul>
                    <li>
                        <label class="radio">
                            <input type="radio" name="formaEnvio" value="195" data-valor="13.93" data-code="transportadora">
                            <b class="prazo">10 dias úteis</b> 
                            <span class="cor-principal valor">
                                R$ 13,93
                            </span> 
                            <span class="nome">Transportadora</span>
                        </label>
                    </li>
                    <li>
                        <label class="radio">
                            <input type="radio" name="formaEnvio" value="59360" data-valor="16.53" data-code="Correios-2">
                            <b class="prazo">
                                15 dias úteis
                            </b> 
                            <span class="cor-principal valor">
                                R$ 16,53
                            </span> 
                            <span class="nome">Correios - SEDEX</span>
                        </label>
                    </li>
                </ul>
            </div>
            <div id="preco-frete" style="display: block;">
                <span class="texto">
                Comprando mais <span id="falta">R$ 32.00</span> ganhe <span>FRETE GRÁTIS!!!</span>
                </span>
            </div>
        <!-- Sobrando </div> -->
        </td>
    </tr>

          <!-- sobrando 
              </td>
            </tr>
          --> 
        </tbody>

-1

The index returns the initial position of the searched Text, if this text is at the beginning of the string it will return to position 0, when it finds nothing it returns -1.

In the case if should be as follows:

if(shirt != -1) {
 ...logica aqui
} else {
  ...
}

Browser other questions tagged

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