Change an element with jquery

3

I have a list of items and each item in this list is a link with a lot of attributes and items within that link.

summarizing my link is like this:

<a href="#" class="editItem list-group-item" data-id="1001" data-validate="2014-09-08">
    <h4>Meu Item</h4>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</a>

What I'm doing is that I click on this item, then it opens a modal that has a form that the user fills in that form and when saving I should update this item, but remembering that I have to change the <a> integer because can have attributes of it altering and texts as well. I've already done all the ajax part, it's sending right, I just can not really replace it.

I tried something like

$.ajax({
    type : 'POST',
    url : 'pagina.php',
    data : dados,
    success : function ( html ) {
        var itens = $("a.editItem");
        $.each(itens, function(i, item) {
            // item_id é uma variavel que tenho que da o item clicado
            if ( $(item).data('id') == item_id ) {

                // AQUI ESTA O MEU PROBLEMA
                $(item).before(html);
                $(item).remove();
            }
        });
    }
});
    
asked by anonymous 13.08.2014 / 22:20

2 answers

3

To replace elements with jQuery you can use .replaceWith () . The syntax is

$(elementosOriginais).replaceWidth(<novo conteudo>);

So in the function where you listen the click can do:

$("a.editItem").on('click', function(){

    var este = this;

    // chamar o ajax
    // etc...
    success : function (html) {
        $(este).replaceWith(html);

And so the clicked element will be replaced with the new one coming from ajax. It is important to var este = this; before ajax, since the this within ajax does not refer to the clicked element;

Note that this method removes all event handlers associated with the removed element. So I suggest delegating the event drop-in to something like:

$(document).on('click', 'a.editItem', function(){

Edit: By the comment you left below I realize that you can not give the var este = this; step. It would be interesting to see the code to see how ajax is called. Anyway you can get the data-id of the element that ajax returns and use that data-id to find the link you want to remove.

Example: link

success: function (html) {
    var este = $('a[data-id="' + $(html).data('id') + '"]');
    este.replaceWith(html);
    
13.08.2014 / 22:28
1

In version 1.9 of jQuery you can try to use .replaceWith ().

The use, in your case, would be something like:

$(item).replaceWith(html);

Now, be smart because the new <a> inserted does not have the callback registered, which means that if you click that new <a> later, it will not call the function that opens the modal window you mentioned earlier.

    
13.08.2014 / 22:42