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

132
Visualizações
Change button styling if element is visible

I would imagine that this is a very simple code solution to fix but I haven't managed to get it functional. To give you some perspective, what I currently have done is a form formatting with intl tel input and then I have included the following code(which works great!) inorder to validate the input;

<span id="valid-msg" class="hide">✓Valid number</span>
<span id="error-msg" class="hide"></span>

<style>
.hide {
        display: none;
}
#valid-msg {
    color: #2b9348;
    
    
}
#error-msg {
        color: #C31014;
    
}
<style>
<!--for validation-->
<script>
var input = document.querySelector("#phone"),
    errorMsg = document.querySelector("#error-msg"),
    validMsg = document.querySelector("#valid-msg");


var updateInputValue = function (event) {
       dialCode.value = "+" + iti.getSelectedCountryData().dialCode;
};
input.addEventListener('input', updateInputValue, false);
input.addEventListener('countrychange', updateInputValue, false);

var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

var reset = function() {
  input.classList.remove("error");
  errorMsg.innerHTML = "";
  errorMsg.classList.add("hide");
  validMsg.classList.add("hide");
};

input.addEventListener('blur', function() {
  reset();
  if (input.value.trim()) {
    if (iti.isValidNumber()) {
      validMsg.classList.remove("hide");
    } else {
      input.classList.add("error");
      var errorCode = iti.getValidationError();
      errorMsg.innerHTML = errorMap[errorCode];
      errorMsg.classList.remove("hide");
    }
  }
});

input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
</script>

What I'm looking to do is change the style of the submit button if the phone number is valid, I thought this might be done by checking if the #valid-msg span was visible or didn't have a class. Here is what I have tried:

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const phoneInput = document.querySelector('#phone');
    const validMsg = document.querySelector('#valid-msg');
    const targetFormButton = document.querySelector('#form-submit');
    if (!phoneInput || !targetFormButton || !validInput) return;

    phoneInput.addEventListener('input', () => {
      const isValid = validMsg.className !== 'hide';
      targetFormButton.classList[isValid ? 'remove' : 'add']('invalid');
      targetFormButton.classList[isValid ? 'add' : 'remove']('valid');
    });
  });
</script> ```

If anyone have suggestions they would be greatly appreciated!
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If your validator works correctly, then what you need is a conditional formatting via class toggle:

const btnSubmit = document.querySelector('#form-submit')
const phoneInput = document.getElementById('phone')
const form = document.getElementById('form')

// simplified validation: valid if more
// than 3 characters long
const validator = (val) => {
  if (val.length < 3) return false
  return true
}

// general function to change classes (add & remove)
// on an element (el)
const validClassToggle = (addClass, removeClass) => (el) => {
  el.classList.add(addClass)
  el.classList.remove(removeClass)
}

// creating setInvalid & setValid functions
const setInvalid = validClassToggle('invalid', 'valid')
const setValid = validClassToggle('valid', 'invalid')

phoneInput.addEventListener('input', function(e) {
  validator(e.target.value) ?
    setValid(btnSubmit) :
    setInvalid(btnSubmit)
})

form.addEventListener('submit', function(e) {
  e.stopPropagation()
  e.preventDefault()
  if (validator(phoneInput.value)) {
    console.log("form submitted")
  } else {
    console.log("form not submitted")
  }
})
.valid {
  background-color: green;
  color: white;
}

.invalid {
  background-color: red;
  color: white;
}
<form id="form">
  <input id="phone" type="text" /><br />
  <button id="form-submit" type="submit">SUBMIT</button>
</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