Create div with append and delete to display another using Jquery

Asked

Viewed 146 times

0

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

I was able to display the error message, only when I click again 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>');
    }
})

1 answer

0


To delete your element use the function remove() 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>');
        }
      });
  • It worked that way when I put 1 field only, but the form has several fields, then I had to do the following ' $.each(errorVal, Function(i, item){ var msgError = '<small class="Alert-error" data-js="Alert-error"> ' + item.defaultMessage + '</small>'; $('#Alert-error').remove(); $('#'+item.field +'-Row').append(msgError); })

  • I changed the answer, please try again.

  • It worked :) thanks!!!

  • For nothing!!!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.