Norbert Girch
Norbert Girch

Reputation: 106

How to prevent jQuery error message prepend more than once

I am prepending an error message to my markup when the field validation fails. The problem is that the prepend works more than once, so a new error message is being displayed every time the user tries to enter bad data. How do I prevent this happening?

Here is my code:

$('#customer-register input[type="submit"]').on('click', function(e) {
  var day = $('#dob_day').val();
  var month = $('#dob_month').val();
  var year = $('#dob_year').val();
  var dateString = day + "/" + month + "/" + year;

  if (isValidDate(day, month, year)) {
    return true;
  }
  e.preventDefault();
  // Show an error here
  $("#customer-register form").prepend("<p>Please enter a valid date.</p>");
  $("#customer-register form p").first().addClass("errors");
});

Upvotes: 0

Views: 15

Answers (1)

samo0ha
samo0ha

Reputation: 3796

you should remove the error message every time you call the function. so add this line $('p.errors').remove(); after event handler.

   $('#customer-register input[type="submit"]').on('click', function(e) {
      $('p.errors').remove();
      var day = $('#dob_day').val();
      var month = $('#dob_month').val();
      var year = $('#dob_year').val();
      var dateString = day + "/" + month + "/" + year;

      if (isValidDate(day, month, year)) {
        return true;
      }
      e.preventDefault();
      // Show an error here
      $("#customer-register form").prepend("<p>Please enter a valid date.</p>");
      $("#customer-register form p").first().addClass("errors");
    });

Upvotes: 2

Related Questions