addEventListener


  • QA Engineer

    There's a form worker.

    window.onload = function() {
    

    d.getElementById('contact_sent').onclick = function(){
    var error_msg = "field is required";
    var error_d = "";
    var elements = document.getElementsByClassName('text_area');
    var errors = document.getElementsByClassName('error');
    var hasError = false;
    for (var i = 0; i < elements.length; i++){
    if (elements[i].value == '' ){
    hasError = true;
    elements[i].style.border = "2px solid orange";
    errors[i].innerHTML = error_msg;
    } else if (elements[i].value != '') {
    elements[i].style.border = "";
    errors[i].innerHTML = error_d;
    }
    }
    return !hasError; } }

    as possible to convert the code using addEventListener by event submit
    I tried that, but even if I made mistakes, the uniform goes away.

    var form = document.getElementById('form');function error(){
    var error_msg = "field is required";
    var error_d = "";
    var elements = document.getElementsByClassName('text_area');
    var errors = document.getElementsByClassName('error');
    var hasError = false;
    for (var i = 0; i < elements.length; i++){
    if (elements[i].value == '' ){
    hasError = true;
    elements[i].style.border = "2px solid orange";
    errors[i].innerHTML = error_msg;
    } else if (elements[i].value != '') {
    elements[i].style.border = "";
    errors[i].innerHTML = error_d;
    }
    }
    return !hasError;}; form.addEventListener('submit',error,false);



  • Try the error function to add a parameter of the event and stop sending the form if there are mistakes.

    function error(e) {
       ...
    

    if (hasError) {
    e.preventDefault();
    }
    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2