Skip to content
Advertisement

What will this code look like in Javascript?

I have problems, I wrote code in Jquery, the worker asks not to use it. This function should check the inputs for fullness

$('document').ready(function() {
    $('#btn').on('click', function() {
      $('.registration__labels .rfield').each(function() {
        if ($(this).val() == '') {
            console.log(2);
            $('input[required]').addClass('error');
        } else {
            console.log(1);
            $('input[required]').removeClass('error');
        }
      });
    });
});

here is the Jquery code, it works

document.addEventListener('DOMContentLoaded',function validation (){
  if(btn.addEventListener("click", function() {
    ('.registration__labels .rfield').forEach(() => {
        if (document.getElementsByClassName('input[type=text]').value == '') {
          console.log(2);
          (".input[required]").classList.add('error');
        }
        else {
          console.log(1);
          (".input[required]").classList.remove('error');
        }
      }
  )}))[validation]});

and this is me trying to translate it into javascript and it doesn’t work. Help me pls

Advertisement

Answer

a way to do that…

window.addEventListener('DOMContentLoaded', () => 
  {
  const allRegLabs = document.querySelectorAll('.registration__labels .rfield')  

  document.querySelector('#btn').onclick = () =>
    {
    allRegLabs.forEach( el =>
      {
      let err =  el.classList.toggle('error', (el.value === ''))
      console.log( (err ? '2':'1' ))
      })
    }
  })
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement