Bug Tracker

Opened 15 years ago

Closed 13 years ago

#2697 closed bug (fixed)

replaceWith should remove before adding

Reported by: scottgonzalez Owned by: flesler
Priority: major Milestone: 1.4
Component: core Version: 1.4a1
Keywords: replaceWith Cc:
Blocked by: Blocking:

Description

See Google Group post for description and possible fix.

Change History (3)

comment:1 Changed 15 years ago by flesler

Owner: set to flesler
Status: newassigned

comment:2 Changed 14 years ago by snaury

I'm surprised that this bug wasn't fixed for a whole year, and I've just been affected by this.

The posting in Google Groups asks for a concrete example, and I have one. I'm creating a Rails application, where I have a _commentform template, that contains a form element, that is submitted with ajax. If there are errors in any fields, then _commentform is rerendered with error messages, and $('#formid').replaceWith('...commentform...') is used to replace old form with the new one.

Later I've added a script tag in that form, that performs some javascript on buttons on the form, using $('#buttonid'). But, unfortunately, when using .replaceWith, scripts are executed when there are *two* elements on the page with the same id, and because old form elements are before new form elements, jQuery picks old buttons (which are later removed), and now I have buttons that don't do what I'd expect.

Needless to say, that Prototype handles this situation correctly, and old elements are removed before new ones are injected, so everything works very well.

Also, I've studied jQuery sources, and it seems that using prev/after/prepend has to do a little more work than next/before/append, so perhaps this implementation would be better than the previous one:

$.fn.replaceWith = function(value) {
  return this.each(function() {
    var e = $(this);
    var s = e.next();
    var p = e.parent();
    e.remove();
    if (s.size())
      s.before(value);
    else
      p.append(value);
  });
}

comment:3 Changed 13 years ago by john

Milestone: 1.2.41.4
Resolution: fixed
Status: assignedclosed
Version: 1.2.31.4a1
Note: See TracTickets for help on using tickets.