Create div with append and delete to display another using Jquery

0

I need to display error validation messages on a form. These messages come from a json when I submit the form. Only a field can have 2 or more msgs, for example: A cpf may have error messages such as: Invalid field or Empty field.

I was able to display the error message, but when I click it it duplicates the message instead of replacing it with a new one. How do I delete the current message and replace it with the new one?

My code is this:

$.each(errorVal, function(i, item){
    console.log("messsagem: " + item.defaultMessage)
    if(item.field === "cpf") {
        $('#cpf-row').append('<small class="alert-error" data-js="alert-error" id="alert-error"> Name: ' + item.defaultMessage + '</small>');
    }
})
    
asked by anonymous 03.09.2018 / 14:53

1 answer

0

To delete your element use the remove() function of JQuery:

$('#alert-error').remove();

$.each(errorVal, function(i, item){
    console.log("messsagem: " + item.defaultMessage)

    if(item.field === "cpf") {
        $('#cpf-row').append('<small class="alert-error" data-js="alert-error" id="alert-error"> Name: ' + item.defaultMessage + '</small>');
        }
      });
    
03.09.2018 / 14:57