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

94
Visualizações
Make an action after two events happened - JS

Want to change submit button color after email verification and checkbox marked. Added listeners on changes and they work well. But have no idea how to find out when this events are going to happen to launch function what is going to change submit button color.

```
https://jsfiddle.net/nvologdins/brfj2xk1/
```
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here is a basic example of how to do this.

I also changed the logic a bit to update the values if the user changes them again. - @Ultimater mentioned this also.


function setupButton() {
  if (validEmail && validCheckbox) {
    // add/show/enable submit button or simply change the color
    button.style.color = "red";
  } else {
    // remove/hide/disable submit button revert the changes
    button.style.color = "";
  }
}
form.input.addEventListener('input', (event)=>{
  validEmail = emailRegex.test(event.target.value);
  setupButton();
})
form.checkbox.addEventListener('change', (event)=>{
  validCheckbox = event.target.checked;
  setupButton();
})

I would also suggest a different method to validate the form using the Constraint Validation API.

Every element has a validity check which can easily be accessed on the form element using formElement.checkValidity() and returns true/false if all (required) fields inside the form are filled with valid values.

<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
  <fieldset>
    <label for="newslettermail">E-Mail</label>
    <!-- you could also define a more specific pattern on the email input since email would allow foo@bar as valid mail -->
    <input type="email" id="newslettermail" required>
  </fieldset>
  <fieldset>
    <input type="checkbox" id="newsletterAcceptTos" required>
    <label for="newsletterAcceptTos">I accept the Terms of Service</label>
  </fieldset>
  <fieldset>
    <label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
    <input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required>
  </fieldset>
  <button type="submit" id="submitButton" disabled>Submit</button>
  <button type="submit">Force submit (will show errors on invalid input)</button>
</form>

Using this, the browser for itself checks the values if they contain a valid value.

  • An input[type=email] with required flag must contain a valid mail address.
  • A checkbox with required flag, must be checked.
  • An input with required and a pattern must contain a value matching the regular expression from the pattern-attribute.
about 4 years ago · Juan Pablo Isaza Relatório

0

No need to create extra variables and listen on two form elements separately... You can check the whole thing and update accordingly only by listening to the form element

let form = document.querySelector('form');
let input = document.getElementById('input');
let checkbox = document.getElementById('checkbox');
let submit = document.getElementById('button');

const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

form.addEventListener('change', (event) => {
  if (checkbox.checked && emailRegex.test(input.value)) {
    submit.style.color = "red";
  } else {
    submit.style.color = "black"
  }
})

//Update
input.addEventListener('input', () => {
  const changeEvent = new Event('change');
  form.dispatchEvent(changeEvent)
})
<form class="main__emailAndTerms emailAndTerms">
  <div class="emailAndTerms__email">
    <input type="text" id="input" placeholder="Type your email address here...">
    <label class="emailAndTerms__terms">I agree to <a href="#"><span class="terms__link">terms of service</span></a>
                <input type="checkbox" class="terms__checkbox" id="checkbox">
                <span class="terms__checkbox_custom"></span>
            </label>
    <button type="submit" class="email__submitButton" id="button">Submit</button>
  </div>
</form>

about 4 years ago · Juan Pablo Isaza 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