3

I have a piece of jQuery code that fills an element on the page with some content:

 var content = $("#note_"+note.id).html();
 $("another_div").html(content);

This replaces the html of the other div fine, but the problem is that any data-remote attributes no longer function on any content inside "another_div". I think the problem is that jquery_ujs is working great for the items on the page at pageload, but if I remotely load content, I lose that functionality.

How do I work around this? I am interested in this as well for its ramifications of remotely loaded partials

jay
  • 12,066
  • 16
  • 64
  • 103
  • what version of Rails are you running? It makes a difference because the jquery-ujs file has changed quite a bit since the 3.0.0 days. – Patrick Klingemann Mar 30 '12 at 22:27
  • Rails 3.0.9 in one app and Rails 3.1.3 (upgraded from 3.0.9 just recently) in the other.. both have the error, both I had run rails g jquery:install on when installing jquery – jay Mar 31 '12 at 00:00

1 Answers1

2

I've experienced this before, the problem is that jQuery has already parsed all of the DOM elements on load, therefore won't be called again automatically when the DOM is changed. You need to manually recall validation parse for your another_div. You can do this by using the following:

$.validator.unobtrusive.parse("#another_div")

Edit: Bit of a hack, but we may need to kick jQuery in the ass

var $main= $("top level tag");

// Unbind validation
$main.unbind();
$main.data("validator", null);

// Reparse document
$.validator.unobtrusive.parse(document);

//Re add to Main
$main.validate($main.data("unobtrusiveValidation").options);
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Hey this sounds like the right direction to go in, but it's not working for me.. maybe i'm doing it wrong though.. – jay Mar 30 '12 at 21:26
  • Are you getting a script error or are the data attributes still not present? – Mathew Thompson Mar 30 '12 at 21:29
  • data attributes present (inspecting element in chrome) but not functional. IE everything looks fine, but for some reason data-remote, data-confirm, or anything similar won't work.. – jay Mar 30 '12 at 21:31
  • Try changing the selector to reparse your entire page? If not, check my edit, bit of a hack, but it may be the only way to brute force JQuery to get it's ass into gear. – Mathew Thompson Mar 30 '12 at 21:34
  • ..yeah nothing seems to work yet.. I'm not sure why though! It may be because I'm using leaflet, and these links are appearing in popups on the map (ie maybe this is extremely case-specific..) – jay Mar 31 '12 at 00:05
  • $.validator.unobtrusive.parse looks like exactly what I've been looking for in a similar situation. Is there any documentation on it anywhere? I've just been looking on the rails ujs git hub site and on jquery docs and couldn't see anything in either of those places... – Edward Mar 31 '12 at 11:41