Ir para conteúdo
Fórum Script Brasil

wash

Membros
  • Total de itens

    398
  • Registro em

  • Última visita

Posts postados por wash

  1. Olá!
    Verifique se seria assim:
     

    import { useState } from 'react'
    
    function Buttons(props) {
      return (
        <button className="verde" onClick={props.clicar}>
          verde
        </button>
      )
    }
    
    const imagens = [
      'https://github.com/fernandoleonid/mini-projetos-js/blob/master/02-semaforo/img/desligado.png?raw=true',
    
      'https://github.com/fernandoleonid/mini-projetos-js/blob/master/02-semaforo/img/verde.png?raw=true',
      'https://github.com/fernandoleonid/mini-projetos-js/blob/master/02-semaforo/img/vermelho.png?raw=true',
    
      'https://github.com/fernandoleonid/mini-projetos-js/blob/master/02-semaforo/img/amarelo.png?raw=true'
    ]
    let timeInterval = () => {}
    
    export default function App() {
      const [imageIndex, setImageIndex] = useState(0)
    
      const TrocarImagem = (novaImagem) => {
        clearInterval(timeInterval)
        setImageIndex(novaImagem)
      }
    
      const Automatico = () => {
        console.log('automatico :>> ')
        timeInterval = setInterval(
          () =>
            setImageIndex((old) => {
              const nextImage = old + 1
              return nextImage >= imagens.length ? 1 : nextImage
            }),
          1000
        )
      }
    
      return (
        <div className="App">
          <div style={{ marginTop: '15px' }}>
            <Buttons clicar={() => TrocarImagem(1)} />
            <button onClick={() => TrocarImagem(2)}>vermelho</button>
            <button onClick={() => TrocarImagem(3)}>amarelo</button>
            <button onClick={Automatico}>automatico</button>
            <img src={imagens[imageIndex]} style={{ width: '20%' }} />
          </div>
        </div>
      )
    }

     

  2. Olá!
    Segue sugestão.
    Considerando que sua $string seja um json válido:

    // decodificar a string como array
    $phpArray = json_decode($string, true);
    
    // data to record
    $dataToRecord = [];
    
    foreach($phpArray['results'] as $v) {
      // desestrutura as variáveis desejadas
      ['id' => $id, 'reason' => $reason, 'auto_recurring' => ['transaction_amount' => $transactionAmount]] = $v;
    
      // guarda em $dataToRecord
      $dataToRecord[] = "('$id','$reason',$transactionAmount)";
    }
    
    // prepara a query de inserção
    $queryToInsert = 'INSERT INTO plano (id, reason, transaction_amount) VALUES '.implode(', ', $dataToRecord);
    
    // exibe na tela
    var_dump($queryToInsert);

     

  3. O php é backend (é interpretado/funciona no servidor)
    Esse tipo de javascript é frontend (é interpretado/funciona no browser)

    Logo, não faz sentido misturar javascript no meio do php
    nem criar vários blocos <script></script>

    Pode-se definir esse trecho javascript uma única vez, depois do html, pois a intenção é que o javascript "rode" depois que todo o html estiver carregado.

    Costuma-se definir o trecho javascript logo antes de fechar a tag body.
    Ex.: 
     

    ...
    <script src='/assets/app.js'></script>
    <script>
    // javascript code here
    </script>
    </body>
    </html>

     

  4. Olá! Você quer o alerta no textarea? Ou digita a placa do veículo num textarea?

    É só escutar o evento input no elemento em que está digitando a placa.
    Quando o texto digitado for suficiente para identificar uma placa única, faça uma requisição à sua api que verifica a existência da placa.

    A partir daí é só resolver com if e else
    se existir, coloque a mensagem no textarea
    se não, faça o que precisar.

    Se não for pra colocar o alerta no textarea, coloque onde precisar.

  5.  

    <!DOCTYPE html>
    <html>
    
    <head>
      <style>
        div div {
          height: 400px;
          width: 500px;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 3px solid black;
          background-color: rgb(186, 235, 243);
        }
    
        div#quadrado img {
          mix-blend-mode: luminosity;
        }
    
        main {
          display: flex;
          justify-content: center;
        }
      </style>
    </head>
    
    <body>
      <main>
        <!-- HTML para criar o quadrado -->
        <div><label>Com filtro</label>
          <div id="quadrado">
            <!-- HTML para adicionar a imagem -->
            <img id="image" src="https://picsum.photos/500/400" alt="imagem">
          </div>
        </div>
        <div><label>Sem filtro</label>
          <div>
            <img src="https://picsum.photos/500/400" alt="imagem">
          </div>
        </div>
      </main>
      <a href="./">Refresh image</a>
      <input type="color" id="colorPicker">
    
      <!-- JavaScript -->
      <script>
    
        // Adiciona um ouvinte de evento para o elemento de entrada de cor
        colorPicker.addEventListener('input', function () {
          // Atualiza a cor da imagem
          quadrado.style.backgroundColor = this.value;;
        });
      </script>
    </body>
    
    </html>



    https://codepen.io/washalbano/pen/abjZBYg

  6. segue sugestão:
     

    <?php
    $jsonData = json_decode('{"items": [
            {
                "index": 1,
                "id": "26845888-7547-3346-800d-9e3ae0353804",
                "uniqueId": "3fc4a0e3-f25e-46f7-a1e4-b66ecdb88152",
                "name": "PEDIDO DE TESTE - MÉDIA (6 PEDAÇOS)",
                "externalCode": "t02",
                "unit": "UN",
                "quantity": 1,
                "unitPrice": 0.00,
                "optionsPrice": 24.00,
                "totalPrice": 24.00,
                "options": [
                    {
                        "index": 2,
                        "id": "a8b24880-b3f6-390a-8514-77bd7b2055aa",
                        "name": "Calabresa",
                        "externalCode": "c02-i002",
                        "unit": "UN",
                        "quantity": 1,
                        "unitPrice": 20.00,
                        "addition": 0.00,
                        "price": 20.00
                    },
                    {
                        "index": 3,
                        "id": "893622be-1730-318e-a486-b2dd4fdfa87d",
                        "name": "Massa Fina + Borda Recheada",
                        "externalCode": "m02",
                        "unit": "UN",
                        "quantity": 1,
                        "unitPrice": 4.00,
                        "addition": 0.00,
                        "price": 4.00
                    }
                ],
                "price": 0.00
            },
            {
                "index": 4,
                "id": "b78d3091-cead-4c12-a06a-1440b3176c77",
                "uniqueId": "663ff728-af46-41ae-bb8d-4ffcc1b961e4",
                "name": "PEDIDO DE TESTE - Bebida teste 100 ml",
                "unit": "GRAMS",
                "quantity": 1,
                "unitPrice": 10.00,
                "optionsPrice": 10.00,
                "totalPrice": 20.00,
                "options": [
                    {
                        "index": 5,
                        "id": "d4603ddd-3519-4fcb-a450-29e06ab5d9ff",
                        "name": "Laranja",
                        "unit": "UN",
                        "quantity": 1,
                        "unitPrice": 10.00,
                        "addition": 0.00,
                        "price": 10.00
                    }
                ],
                "price": 10.00
            },
            {
                "index": 6,
                "id": "e8f9f490-2a56-4bb8-a9d3-5e9b72fe027c",
                "uniqueId": "98de1e93-ba34-48bb-8f75-1b8c21e43fd1",
                "name": "PEDIDO DE TESTE - Sanduíche",
                "externalCode": "c01-i001",
                "unit": "GRAMS",
                "quantity": 1,
                "unitPrice": 20.00,
                "optionsPrice": 1.00,
                "totalPrice": 21.00,
                "options": [
                    {
                        "index": 7,
                        "id": "1101565b-dc4b-44d3-9e82-b7c4b07397f3",
                        "name": "Complemento 1",
                        "unit": "UN",
                        "quantity": 1,
                        "unitPrice": 1.00,
                        "addition": 0.00,
                        "price": 1.00
                    },
                    {
                        "index": 8,
                        "id": "42e8a1f3-6f3e-4370-9223-05464f5be701",
                        "name": "Complemento 6",
                        "unit": "UN",
                        "quantity": 1,
                        "unitPrice": 0.00,
                        "addition": 0.00,
                        "price": 0.00
                    }
                ],
                "price": 20.00
            }
        ]}');
    
    foreach ($jsonData->items as $v) {
      echo '<pre>$v: ';
      print_r($v);
      echo '</pre>';
    }

     



  7. Seu script pode ficar mais elegante assim:
     

    <head>
      <meta charset="utf-8" />
      <title>Salário</title>
      <style>
        input[type="text"] {
          text-transform: capitalize;
        }
      </style>
    </head>
    
    <body>
    
      <form action="" method="post">
        Digite o mês (1 a 12): <input type="number" size="4" step="1" min="1" max="12" />
        <p></p>
        <p></p>
        O Mês correspondente a: <input type="text" size="18" maxlength="15" />
      </form>
    
      <script>
        const setMonthName = (date) => {
          document.querySelector('input[type="text"]').value = new Intl.DateTimeFormat("pt-BR", { month: "long" }).format(date);
        }
    
        document.querySelector("input[type='number']").onchange = (e) => {
          setMonthName(new Date(2022, e.target.value - 1, 01))
        }
      </script>
    </body>

     

    https://codepen.io/washalbano/pen/NWBNaVO

  8. 17 minutos atrás, Frank K Hosaka disse:

    eu não sei o que é aquele [...arr]. Você já viu um negócio desses?

    Bão sr. @Frank K Hosaka?
    Eu já vi!
    Isso daí se chama spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    No caso da função median foi usado para não alterar o array original, uma vez que no js se passa a referência da variável, 

    se usasse vr.sort(), o array vr seria reordenado
    logo, ao espalhar o conteúdo de vr em num novo array: [...vr].sort(... o array original foi preservado e essa nova referência de dado em memória foi atribuída à variável nums

    em outras palavras:
    o spread operator foi usado apenas para fazer uma cópia do array

×
×
  • Criar Novo...