Ir para conteúdo

POWERED BY:

joeythai

2 eventos conflitando

Recommended Posts

Boa tarde pessoal,

 

Estou tendo um problema com 2 eventos aqui do javascript, eu tenho essa variável numberInstallments que representa um combo select, nesse combo tem 36 opções que representam  a quantidade de parcelas, e dependendo da quantidade de parcelas que eu escolho eu imprimo um texto, exemplo: (se for menor ou igual a 11 parcelas) "Estou pagando o valor de <signalValueInstallment>" num total de 11 parcelas. 

 

Se eu alterar o valor da parcela e manter a quantidade de parcelas o texto deve permanecer, porém, o <signalValueInstallment> deve ser alterado, esta variável é alterada pelo input que tenho no formulário, nesse input tem outro evento de keyup. Está funcionando mais ou mentos, eu consigo alterar o valor do input e ele altera no texto, o problema é que só está aparecendo o texto 2 que deveria aparecer somente para parcelas superiores a 11 parcelas. Alguem sabe dizer o que está errado aí ?

 

 

 

 

 

 

149396870_WhatsAppImage2022-10-27at17_14_59.thumb.jpeg.e63e4cc07ff9afe038215ac34f2b93e9.jpeg

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom você está cometendo um equivoco entre a identificação numberInstallments e o elemento dom html essá variavel presuponho conter apenas um ID ou CLASS sendo assim não contém o mapeamento do valor do input

 

EX:

const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function() { // missing event variable
 
  // why is there such a dependency beetween these 2 events 'change' and 'keyup'?
  // I think it's better to uncouple!
  $(signalValueInstallment).on('keyup', function(event) {
    
    // numberInstallments is only a simple string, is not possible to handle the dom element this way.
    // That is the reason  it doesn't not work as expected
    if(numberInstallments.value <= 11){  
      $(description).html('Texto teste 1 R$ ' +signalValueInstallment.value +' .Fim test.');// same here
    }else{
      $(description).html('Texto teste 2 R$ ' +signalValueInstallment.value +' .Fim test.');// same here
    }
  })
})

Outra possibilidade é substituir numberInstallments.value por $(numberInstallments ).val() que é a forma especifica para recuperar valor usando o jquery, mas acredito que você consiga simplemente reutilizando as variaveis de evento assim não precisa processar a busca no dom novamente, já que essa ação já foi realizada.

 

Ex:

const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function(e) {// add event parameter
  const selectorValue =  e.target.value; // add variable to get select value
  
  $(signalValueInstallment).on('keyup', function(event) {
    const inputValue =  event.target.value; // add variable to get input value
    
    if(selectorValue <= 11){
      $(description).html('Texto teste 1 R$ ' +inputValue +' .Fim test.');
    }else{
      $(description).html('Texto teste 2 R$ ' +inputValue +' .Fim test.');
    }
  })
})

Jsbin: https://jsbin.com/hayicasoro/1/edit?html,js,output

 

Ex código um pouco desacoplado

const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function(event) {
  const selectorValue =  event.target.value;
  const inputValue =  $(signalValueInstallment).val();
  
  handleInstallment(selectorValue, inputValue);
})

$(signalValueInstallment).on('keyup', function(event) {
  const selectorValue =  $(numberInstallments).val();
  const inputValue =  event.target.value;
    
  handleInstallment(selectorValue, inputValue);
})

function handleInstallment(selectorValue, inputValue){  
  if(selectorValue <= 11){
    $(description).html('Texto teste 1 R$ ' +inputValue +' .Fim test.');
  }else{
    $(description).html('Texto teste 2 R$ ' +inputValue +' .Fim test.');
  } 
}

Jsbin: https://jsbin.com/cuwamahafo/1/edit?html,js,output

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 28/10/2022 at 19:22, wanderval disse:

Bom você está cometendo um equivoco entre a identificação numberInstallments e o elemento dom html essá variavel presuponho conter apenas um ID ou CLASS sendo assim não contém o mapeamento do valor do input

 

EX:


const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function() { // missing event variable
 
  // why is there such a dependency beetween these 2 events 'change' and 'keyup'?
  // I think it's better to uncouple!
  $(signalValueInstallment).on('keyup', function(event) {
    
    // numberInstallments is only a simple string, is not possible to handle the dom element this way.
    // That is the reason  it doesn't not work as expected
    if(numberInstallments.value <= 11){  
      $(description).html('Texto teste 1 R$ ' +signalValueInstallment.value +' .Fim test.');// same here
    }else{
      $(description).html('Texto teste 2 R$ ' +signalValueInstallment.value +' .Fim test.');// same here
    }
  })
})

Outra possibilidade é substituir numberInstallments.value por $(numberInstallments ).val() que é a forma especifica para recuperar valor usando o jquery, mas acredito que você consiga simplemente reutilizando as variaveis de evento assim não precisa processar a busca no dom novamente, já que essa ação já foi realizada.

 

Ex:


const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function(e) {// add event parameter
  const selectorValue =  e.target.value; // add variable to get select value
  
  $(signalValueInstallment).on('keyup', function(event) {
    const inputValue =  event.target.value; // add variable to get input value
    
    if(selectorValue <= 11){
      $(description).html('Texto teste 1 R$ ' +inputValue +' .Fim test.');
    }else{
      $(description).html('Texto teste 2 R$ ' +inputValue +' .Fim test.');
    }
  })
})

Jsbin: https://jsbin.com/hayicasoro/1/edit?html,js,output

 

Ex código um pouco desacoplado


const numberInstallments = '#numberInstallments';
const signalValueInstallment = '#signalValueInstallment';
const description = '#description';

$(numberInstallments).on('change', function(event) {
  const selectorValue =  event.target.value;
  const inputValue =  $(signalValueInstallment).val();
  
  handleInstallment(selectorValue, inputValue);
})

$(signalValueInstallment).on('keyup', function(event) {
  const selectorValue =  $(numberInstallments).val();
  const inputValue =  event.target.value;
    
  handleInstallment(selectorValue, inputValue);
})

function handleInstallment(selectorValue, inputValue){  
  if(selectorValue <= 11){
    $(description).html('Texto teste 1 R$ ' +inputValue +' .Fim test.');
  }else{
    $(description).html('Texto teste 2 R$ ' +inputValue +' .Fim test.');
  } 
}

Jsbin: https://jsbin.com/cuwamahafo/1/edit?html,js,output

 

Muito obrigado, resolveu meu problema, no caso foi a segunda opção. só não estou conseguindo "reagir" para marcar sua resposta como solução.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Que bom que ajudou, sobre reagir ao post fica tranquilo eu to com esse numero 19 já faz mais de 4 anos, embora esse forum esteja ativo, acho que a equipe de desenvolvimento já não atualiza ou corrigi os bugs!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por luiz monteiro
      Olá.
      Estou atualizando meu conhecimento com Front-End e me deparei com o seguinte problema.
      Criei um sistema para fazer o upload de imagens e alguns campos text.
      Algo bem simples para depois começar a estudar javascript para mostrar a miniatura....
      Mas quando saio do navegador Chrome ou da aba por mais de 3 minutos, ao retornar o navegador as vezes atualiza ou nem chega atualizar mas limpa os campos.
      Estou usando um Smart Motorola com Android, mas um amigo testou no iPhone e acontece a mesma coisa.
      Gostaria de saber se há como usar javascript para evitar isso?
      Agradeço desde já.

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Uploader</title>
      </head>
      <body>
          <form action="?" method="post" enctype="multipart/form-data">
              <br><br>
              <div>selecione a imagem 1</div>
              <input type="file" name="foto1" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem1">
              
              <br><br>
              <input type="file" name="foto2" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem2">
              
              <br><br>

              <input type="file" name="foto3" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem3">
              
              <br><br>
              <input type="submit" value="Enviar">
              <br><br>
          </form>
      <?php
      if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
          vardump ($_FILES);
      }
      ?>
      </body>
      </html>
       
       
       
    • Por belann
      Olá!
       
      Estou usando o nextjs versão 15.2.3 e criei uma navbar que quando é carregado o programa aparece com a home, mas na hora de clicar na página produtos desaparece a navbar.
      A navbar esta sendo chamada no layout.tsx estou usando typescript
      e fica dessa forma
      <div>           <Navbar/>             <main>{children}</main>             </div>  
    • Por violin101
      Caros amigos, saudações.

      Estou com uma dúvida, referente cálculo de valores em tempo real.

      Tenho uma rotina, que faz o cálculo, o problema é mostrar o resultado.

      Quero mostrar o RESULTADO assim: 0,00  ou  0.00

      Abaixo posto o código.
      jQuery('input').on('keyup',function(){ //Remover ponto e trocar a virgula por ponto var m = document.getElementById("pgRest").value; while (m.indexOf(".") >= 0) { m = m.replace(".", ""); } m = m.replace(",","."); //Remover ponto e trocar a virgula por ponto var j = document.getElementById("pgDsct").value; while (j.indexOf(".") >= 0) { j = j.replace(".", ""); } j = j.replace(",","."); m = parseFloat(jQuery('#pgRest').val() != '' ? jQuery('#pgRest').val() : 0); j = parseFloat(jQuery('#pgDsct').val() != '' ? jQuery('#pgDsct').val() : 0); //Mostra o Resultado em Tempo Real jQuery('#pgTroco').val(m - j); <<=== aqui estou errando })  
       
      Grato,
       
      Cesar
       
       
    • Por violin101
      Caro amigos, saudações.

      Tenho uma tabela escrita em JS que funciona corretamente.
       
      Minha dúvida:
      - como devo fazer para quando a Tabela HTML estiver vazia, exibir o LOGO da Empresa ?

      Abaixo posto o script:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'i' ) return;// Não é Ctrl+A, portanto interrompemos o script evt.preventDefault(); //Chama a Função Calcular Qtde X Valor Venda calcvda(); var idProdutos = document.getElementById("idProdutos").value; var descricao = document.getElementById("descricao").value; var prd_unid = document.getElementById("prd_unid").value; var estoque_atual = document.getElementById("estoque_atual").value; var qtde = document.getElementById("qtde").value; var vlrunit = document.getElementById("vlrunit").value; var vlrtotals = document.getElementById("vlrtotal").value; var vlrtotal = vlrtotals.toLocaleString('pt-br', {minimumFractionDigits: 2}); if(validarConsumo(estoque_atual)){ //Chama a Modal com Alerta. $("#modal_qtdemaior").modal(); } else { if(qtde == "" || vlrunit == "" || vlrtotal == ""){ //Chama a Modal com Alerta. $("#modal_quantidade").modal(); } else { //Monta a Tabela com os Itens html = "<tr style='font-size:13px;'>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='id_prds[]' value='"+idProdutos+"'>"+idProdutos+"</td>"; html += "<td width='47%' height='10'>"+ "<input type='hidden' name='descricao[]' value='"+descricao+"'>"+descricao+ "<input type='hidden' name='esp[]' value='"+prd_unid+"'> - ESP:"+prd_unid+ "<input type='hidden' name='estoq[]' value='"+estoque_atual+"'></td>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='qtde[]' value='"+qtde+"'>"+qtde+"</td>"; html += "<td width='12%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrunit[]' value='"+vlrunit+"'>"+vlrunit+"</td>"; html += "<td width='14%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrtotal[]' value='"+vlrtotal+"'>"+vlrtotal+"</td>"; html += "<td width='12%' height='10' style='text-align:center;'>"+ "<button type='button' class='btn btn-uvas btn-remove-produto' style='margin-right:1%; padding:1px 3px; font-size:12px;' title='Remover Item da Lista'>"+ "<span class='fa fa-minus' style='font-size:12px;'></span></button></td>"; html += "</tr>"; $("#tbventas tbody").append(html); //Função para Somar os Itens do Lançamento somar(); $("#idProdutos").val(null); $("#descricao").val(null); $("#prd_unid").val(null); $("#qtde").val(null); $("#vlrunit").val(null); $("#vlrtotal").val(null); $("#idProdutos").focus(); //Se INCLUIR NOVO produto - Limpa a Forma de Pagamento $("#pgSoma").val(null); $("#pgRest").val(null); $("#pgDsct").val(null); $("#pgTroco").val(null); $("#tbpagar tbody").empty(); }//Fim do IF-qtde }//Fim do Validar Consumo });//Fim da Função btn-agregar  
      Grato,

      Cesar
       
    • Por violin101
      Caros amigos, saudações.

      Estou com uma pequena dúvida se é possível ser realizado.

      Preciso passar 2 IDs para o Sistema executar a função, estou utilizando desta forma e gostaria de saber como faço via JS para passar os parâmetro que preciso.

      Observação:
      Dentro da TABELA utilizei 2 Forms, para passar os IDS que preciso, funcionou conforme código abaixo.
      <div class="card-body"> <table id="tab_clie" class="table table-bordered table-hover"> <thead> <tr> <th style="text-align:center; width:10%;">Pedido Nº</th> <th style="text-align:center; width:10%;">Data Pedido</th> <th style="text-align:center; width:32%;">Fornecedor</th> <th style="text-align:center; width:10%;">Status</th> <th style="text-align:center; width:5%;">Ação</th> </tr> </thead> <tbody> <?php foreach ($results as $r) { $dta_ped = date(('d/m/Y'), strtotime($r->dataPedido)); switch ($r->pd_status) { case '1': $status = '&nbsp;&nbsp;Aberto&nbsp;&nbsp;'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#000000'; //Cor: Preta break; case '2': $status = 'Atendido Total'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#086108'; //Cor: Verde break; case '3': $status = 'Atendido Parcial'; $txt = '#000000'; //Cor: Branco $cor = '#FEA118'; //Cor: Amarelo break; default: $status = 'Cancelado'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#D20101'; //Cor: Vermelho break; } echo '<tr>'; echo '<td width="10%" height="10" style="text-align:center;">'.$r->pd_numero.'</td>'; echo '<td width="10%" height="10" style="text-align:center;">'.$dta_ped.'</td>'; echo '<td width="32%" height="10" style="text-align:left;">'.$r->nome.'</td>'; echo '<td width="10%" height="10" style="text-align:left;"><span class="badge" style="color:'.$txt.'; background-color:'.$cor.'; border-color:'.$cor.'">'.$status.'</span></td>'; echo '<td width="5%" style="text-align:center;">'; ?> <div class="row"> <?php if($this->permission->checkPermission($this->session->userdata('permissao'), 'vPedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/visualizar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-warning" title="Visualizar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-search icon-white"></i></button> </form> <?php } if($this->permission->checkPermission($this->session->userdata('permissao'), 'ePedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/editar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-primary" title="Editar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-edit icon-white"></i></button> </form> <?php } ?> </div> <?php echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div>
      Grato,

      Cesar.
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.