What's the best practice to prevent an element from getting duplicated, when an event handler is called?

Hi,

I’ve been doing and learning jQuery coding practices by reading a book based off of it. I’m using form validation in my code here:

var $fieldElement = $('input, textarea'),
    errMsg = '';
    
$fieldElement.on('keyup blur', function() {
  var $current = $(this),
      $errorDiv = $('<div class=".error">' + errMsg + '</div>');
  
  if($current.attr('required')) {
    errMsg = $current.attr('data-error-message');
    
    if($current.val().length > 0) {
      $current.parent('div').addClass('fillingStart');
      if($current.next('.error')) {  
        $current.next().remove();
      }
    }
    else {
      //Remove the appearing label
      $current.parent('div').removeClass('fillingStart');
      if($current.next('error').length === 0) {
        //Append the descendant sibling to display the error.
        $current.parent('div').append($errorDiv);
      }
    }
    if($current.attr('type') === 'email') {
      //Do something here.
    }
  }
});

The rest of the code such as the HTML/CSS code is shown via JSFiddle

Each time the event handler gets invoked, the “div” element that I set to append, gets duplicated each time when the event is triggered via “keyup” and “blur”. When I also hit the backspace button on my keyboard, the div element also gets duplicated. What’s the best practice for me to stop the newly created element from being copied each time the event gets triggered?

Thanks! :confused:

Hi.

  1. Class name shouldn’t start with dot here:

    $errorDiv = $(‘

    ’ + errMsg + ‘
    ’);

  2. Missed dot in class name here:

    if($current.next(‘error’).length === 0) {

  3. Make errMsg variable local

Fixed version here: https://jsfiddle.net/n7ebafoy/8/

Didn’t realize I made an error. Thanks :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.