Search code examples
javascripterror-handlingappendchildcreatetextnode

JavaScript Live Error Display?


I need an efficient way to display errors I've collected from a form onsubmit function. Here is my error collecting function:

function checkForm(form) {

 var errors = "";

 errors += checkName(form, form.name.value);

 errors += checkSex(form, form.sex.value);

 if(form.gender[0].checked || form.gender[1].checked) {
      errors += checkGender(form, true);
 } else {
  errors += checkGender(form, false);
 }

 errors += checkHeight(form, form.height.value);

 errors += checkSalary(form, form.salary.value);

 errors += checkCountry(form, form.birthCountry.value);

 if(errors) {
        document.getElementById("errors").appendChild(document.createTextNode(errors));
  return false;
 }

 return true;

}

Unfortunately it seems that createTextNode() doesn't process new lines ( \n ) or HTML. How can I get past this? Or are there any other alternative, more efficient solutions?


Solution

  • In HTML, newlines and whitespace in general is ignored. To force a line break, you have to use the br tag. You could easily run a replace on the errors string, or just make the functions add those tags instead of a newline.

    errors.replace( '\n', '<br />' )
    

    You can then just append that to the element's innerHTML:

    document.getElementById( 'errors' ).innerHTML += errors.replace( '\n', '<br />' );