Mi Ro
Mi Ro

Reputation: 760

jquery validate rails dynamically named form

I have a form dynamically named by rails like "edit_project_id" where ID changes. How to enable jquery validate for any form "edit_project%" ?

I tried to pass name to my javascript/coffee as data attribute according this http://railscasts.com/episodes/324-passing-data-to-javascript but with no luck

I've added this tag to pass name variable

<%= content_tag "div", id: "form_name", data: {name: "edit_user_#{@project.id}" } %>

then in my coffee I try to work with it but no luck

jQuery -> 
$('#form_name').data('name').validate(
     lang: 'sk'
     rules:
        'project[amount]': min: 1
     highlight: (element) ->
        $(element).parent().addClass 'state-error'
        return
     unhighlight: (element) ->
        $(element).parent().removeClass 'state-error'
        return
);

at the end I want my coffee script to validate each form which is for edit_project doesnt matter ID..if it is possible with some wildcard or passing variables, both is ok for me, just dont know how to do that

Upvotes: 0

Views: 323

Answers (1)

Sparky
Sparky

Reputation: 98738

I have a form dynamically named by rails like "edit_project_id" where ID changes. How to enable jquery validate for any form

FYI - the .validate() method does not need to be attached to the id. You can use any valid jQuery selector you can imagine. The only requirement is that the selector can only target ONE form, not a group of forms.

So if you only have one form on the page, you can simply target the <form> tag itself...

$('form').validate({ ...

If that's not acceptable, then inspect the rendered DOM and construct a reliable jQuery selector based on some other set of criteria.


To target the data attribute when it "starts with" something like edit_user...

$('[data^="edit_user"]').validate({ ...

And if you have more than one form matching the selector, wrap it in an .each() and .validate() will be attached to all matching forms..

$('[data^="edit_user"]').each(function() {
    $(this).validate({ ...

Upvotes: 1

Related Questions