Complex Forms - how to generate new object_ids for each new element?
Through a combination of logic and a lack of experience with JQuery/Javascript, I have found myself with this problem.
Background -
I am using the Jquery-deep branch of Complex-Form-Examples, which enables a form that creates/edits records for multiple nested tables at once. Part of this is the ability for the user to dynamically add/delete new records. Example: a user can create a Project (level A) with many Tasks (level B), each with many Assignments (level C).Javascript additions -
I have built a javascript function that applies independently to each Task. When a user selects from a select box, "true" has the id:"multiple_choice_" + f.object_id.to_s
, and the function finds this and highlights a div called "true_" + f.object_id.to_s
.
New elements don't have new object_id's -
Every time a user adds a new record, they all have the same object_id, which makes my above plan useless. I tried adding this object_id to arand(1000000000)
but even that is identical each time a new Task is added.
How can I either (1) generate new object_ids / random numbers each t开发者_JAVA百科ime a Task is added, or (2) use a different unique identifier for each task that will be different for each addition?
Add_child code in application.js:
$(function() {
$('form a.add_child').live('click', function() {
var assoc = $(this).attr('data-association');
var content = $('#' + assoc + '_fields_template').html();
var regexp = new RegExp('new_' + assoc, 'g');
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
return false;
});
});
Clarification
The problem is not how to generate a random number in the .js code above. The problem is how to access that new random number from within the newly generated code to, for example, form the ID of an html element.
Just use global counter:
var _taskCount = 0;
$(function() {
$('form a.add_child').live('click', function() {
...
var new_id = "Task_" + _taskCount;
_taskCount++;
...
});
});
精彩评论