views:

100

answers:

1

Consider the following partial, it gets inserted into a page if someone clicks ajax "add comment" link. The question I have is: Is this the best place to include that javascript?

I thought it was best to put it in the application.js, but because the partial gets added via ajax, the validate method called within $(document).ready block does not get triggered because the form does not exist when the original document is ready. Does that make sense?

Using Rails 2.3.4 and jQuery 1.4.1

Thanks!

<%form_for [@commentable,@comment] do |f|%>
  <%= f.text_area :comment, :class=>"required", :minlength=>2%>

  <% content_tag :button, :type => :submit do %>
    Comment
  <% end %>
<%end%>

<script type="text/javascript">
  $(document).ready(function(){
    $("#new_comment").validate();
  });
</script>
+1  A: 

Not sure when you want the validation to occur, but it seems like you could use jquery's live functionality to attack a valiation method defined in your application.js to the incoming partial's submit button.

I was thinking something along the lines of:

$("#new_comment").live('click', function(event) {
  $(this).validate();
  // or maybe event.target.validate(); ?
});
Ckhrysze
what would the syntax of that be? I found http://api.jquery.com/live/ but unclear how to apply it in this situation. $("#new_comment").live('validate'); in application.js does not seem to work
Jonathan
This was the syntax that I got it to work with:$("#new_comment").live('click', function() { $(this).validate();});
Jonathan
Glad it worked! I updated the answer to reflect the syntax that was used.
Ckhrysze