1

I have a basic form in html, when user leave blank fields I show a message in spans that I created via javascript, so far so good. But if I click 'submit' button again and again, the messages are printed again and again Above the message that has already been printed, I mean overlapping.

I tried the element.innerHTML = ''; and this. Maybe I'm implementing it badly since it does not work.

var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');

myForm.addEventListener('submit', function(){
  event.preventDefault(); 
    var statusMessageHTML = [];     
    // create empty spans
    for(i = 0; i < formFields.length; i++){
      statusMessageHTML[i] = document.createElement('span');
        statusMessageHTML[i].className = 'status-field-message';
      formFields[i].appendChild(statusMessageHTML[i]);     
    }
    // print a string in empty spans
    for(i = 0; i < formFields.length; i++){
      statusMessageHTML[i].innerHTML = "Error Message"
    }      
  return false;
});

PD: I want to solve this using pure javascript.

CODEPEN

GhostOrder
  • 586
  • 7
  • 21

1 Answers1

1

To prevent this, you can create and append those spans in advance, and just modify their text when the submit button is clicked.

For example, rearrange your code as following:

var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');

// create empty spans in advance
var statusMessageHTML = [];
for(var i = 0; i < formFields.length; i++) {
  statusMessageHTML[i] = document.createElement('span');
  statusMessageHTML[i].className = 'status-field-message';
  formFields[i].appendChild(statusMessageHTML[i]);
}

myForm.addEventListener('submit', function(event) {
  event.preventDefault();
  
  // change the text of spans
  for(var i = 0; i < formFields.length; i++)
    statusMessageHTML[i].textContent = 'Error Message';
});

Note:

  • You have to include corresponding variable name (i.e., event) in the function's parameters before using it.
  • span.textContent may be preferable to span.innerHTML in your case.
  • It is pointless to return a value in the addEventListener's callback function. The returned value is simply discarded.
  • It is a good practice to declare all variables (e.g., i) before using them.
  • You can also construct those spans directly in HTML, since they are kind of "static" in the structure.

Updated

If I understand it correctly, you prefer:

  • Create those spans as placeholders when it is the first time the user submits.
  • Rewrite values in spans when the response of the ajax request is received.
  • If the submit button is clicked multiple times, just clear previous values in spans, and the following process remains the same.

Then I believe you just need to wrap the whole part in a if-else block:

var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
var statusMessageHTML = [];
var isFirstSubmit = true;

myForm.addEventListener('submit', function(event) {
  event.preventDefault();

  if(isFirstSubmit) {

    // create empty spans
    for(var i = 0; i < formFields.length; i++) {
      statusMessageHTML[i] = document.createElement('span');
      statusMessageHTML[i].className = 'status-field-message';
      formFields[i].appendChild(statusMessageHTML[i]);
    }
    
    isFirstSubmit = false;
    
  } else {
    
    // clear previous values
    for(var i = 0; i < formFields.length; i++)
      statusMessageHTML[i].textContent = '';
      
  }
});

And rewrite the values when you get the response (possibly wrapped in a callback function, since it is an AJAX request):

function callback(response) {
  for(var i = 0; i < formFields.length; i++)
    statusMessageHTML[i].textContent = /*values in response*/;
}
Community
  • 1
  • 1
Microloft
  • 345
  • 1
  • 7
  • Thanks for the answer @Microloft this is the only way to prevent this? I'm new in develop in general, so please correct me if I'm wrong. I would prefer to keep the creation code inside the submit function, because this way spans only be created when the user submit the form (before that there is not need to have those spans), this way the initial page load would be a little bit.... faster? I mean, just a little bit. This is my reasonning behind why I would prefer create those spans only when they are useful (to show error mesage when user submit a form). – GhostOrder Aug 06 '17 at 21:13
  • I see what you mean, but it is still not clear to me what you are trying to accomplish. If the submit button is clicked multiple times, are you going to remove existing `span`s and create a whole new set, or just jump over that part? If the user finally submits successfully, are you going to remove those existing `span`s as well? – Microloft Aug 07 '17 at 07:03
  • Ideally I would like to create the spans only when a error message is sended from php, but then I would need to do the validation also in js, right? And I prefer use only php with ajax for this form(I know there isn't one in my code, I just put "Error message" as example to save lines). So, to answer the question, if the submit button is clicked multiple times, I would like to clear the innerHTML of the spans first and then rewrite the value returned from my ajax request in them(Currently, if my php detect there is not errors just send a empty string. Btw i don't know if is a good practice). – GhostOrder Aug 07 '17 at 23:49
  • Thanks for the help @Microloft, now it's working as I wanted it to be. And thanks for the advices too. – GhostOrder Aug 08 '17 at 04:40