I’m using devise in my rails 3.2 application.
I have a users/new page where an admin user fills in an email address and then a user is created with a random password.
All of this works fine.
What I want to do is to create a dynamic form so that the admin can create as many users as they want. There should be an ‘add user field’ button and a ‘delete user field’ button that allows generation of new fields for users.
I can’t seem to get the jquery to work with the form.
I tried using what was described in this stackoverflow question:
My code is like this (Note I’m using @manager instead of @user in the form so as not to confuse rails with the current_user. Still @manager creates a devise user.
users/new
<%= form_for(@manager) do |f| %>
<% if @manager.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@manager.errors.count, "error") %> prohibited this manager from being saved:</h2>
<ul>
<% @manager.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<span class="add">Add fields</span>
<div class="actions">
<%= f.submit %>
app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require_tree .
$(document).ready(function() {
$(".add").click(function() {
$(".field:first").clone(true).insertBefore(this);
return false;
});
});
Still, when I click on Add fields, nothing happens. I’m pretty sure if I can get the form to submit the right parameters, then I can work the controller to do what I want it to do.
Basically, why isn’t the clone function working in the above example and how can I get a dynamic form to create multiple devise users at once.
Also, I left out the delete fields method since it obviously isn’t working either.
EDIT: I changed the selector to “.add” and I changed “.field” to “.field:first”, but it’s still not working.
“add” is not a valid selector…. you need a “.” prefix to represent that it is for a class. Without prefix you are looking for a tagName of “add”
http://api.jquery.com/category/selectors/
If you click more than once you will then be adding as many elements with class=”field” as exist in form due to your “.field” selector.
You should probably use something like: