I have a nested form in my app that uses AJAX to load an additional sets of fields. One of those fields is a file upload that I want to hide and effectively replace with a text field for pasting a Youtube link. It works for the first sets of fields, however since the function is bound on document.ready, it doesn't work for new AJAX fields. I need to bind it some other way. What do?
$ ->
$(".foo").click ->
$(this).css "display", "none"
Update: I wasn't having luck, so I went to read the jQuery .on() documentation, and it reminded me of what Fresheyeball said about binding it on to a parent div. After that, it worked perfectly. Thanks for the great advice!
$ ->
$("#create").on "click", ".foo", ->
$(this).css display : "none"
The new jQuery .on should work for you:
$(document).ready ->
$(window).on 'click', '.multiswitchr', ->
that = $(this)
that.css display : 'none'
that.closest(".fields").find(".f-upload").first().css display : "none"
that.closest(".fields").find(".attachment-holder").first().css display : "none"
that.closest(".fields").find(".youtube-link").first().css display : "inline"
The way this work is it binds the listener to window
(or you can use the direct parent) to listen for the existence of .multiswitchr
and binds the 'click'
event to it.
P.S. in coffeescript the shorthand for document ready is just $ ->
document
element. When an event bubbles-up to the initial selection, the selector passed to the .on()
(second argument) function is checked against and if it matches the target of the event, the event handler fires (in a manor that makes this
inside the event handler reference the delegated element) - Jasper 2012-04-05 22:53