Currently, I allow my users to dynamically add new fields to a form
using the link_to_function variable. However, whenever a new field is
added, its inputs have the same names as the previous fields. I
solved this by passing in a local variable, but I can't get that value
to increment (or update) on click.
(Yes, that code was take from ryan bates's complex forms series.)
How do I get that :num => 1 to increment every time a user clicks "Add
Another." increment and increment! don't seem to work, and I thought
about using Time.now.to_i instead of single digit integers (note: it
doesn't matter what "num" is as long as it's a number), but that only
loads the time when page is first loaded, and doesn't update when "Add
Another" is clicked.
So, is there anyway to increment this :num value using client side
javascript?
hmm... I figured it would be easy. then I played with it. It is not
easy. I was able to get it working in pure javascript, but could not
get it working in rails... maybe someone else can get it, but it
seemed to me rails was loading the partial as part of the link AKA the
local is set when the link is created.
if you want to see it working in JavaScript it is not too hard. The
Main pain is no partial use, you gotta build the partial in the
link...
<code>
<script language="javascript">
var count = 0;
function getCount() {
return count++;
}
</script>
I am sure there are a million ways to do it, and some may be better,
but I am pretty sure link_to_function will not be in the answer to
many if any of them.
Why do you want to use javascript to increment the field count? This
seems like it'd be so much easier to just store the field count in the
session and be done with it.
An example for a webmail app I hacked out awhile ago (though I'm still
not sure this counting approach in general is the best way to do
things:)
I'm using each_with_index, but can't the index value to update each
time the user "Adds Another", which is why I was defining a new
variable and passing it as well. So I guess that's my real problem,
getting each_with_index to update.
Your pure javascript way is great!, and a lot cleaner than the
link_to_function, which I don't really like anyway. Is there a way to
pass in the partial with your javascript method? Like instead of
"input type='text' name='random_input_"", how can I pass in
":partial => 'stuff', :object => Feed.new" and use getCount() as
the :num?
Sorry, I really am noob when it comes to raw Javascript. I've been
playing around with it and can't get it to work. I do think this way
will be perfect though, so thank you for your help, much appreciated.