开发者

Auto generate HTML element IDs in Rails when repeating the same control through partials

I am using partials in Rails combined with jQuery child field templates to dynamically generate forms with multiple nested child attributes. Within these partials is JavaScript that is fired when various events (e.g. onChange) occur in the form, and the code that executes needs to change the DOM for a related but different form element. In this particular case, I'm using it to add multiple sale transactions in a point-of-sale type solution to a particular group of transactions and control what data is collected for each transaction. So, for example:

  1. User clicks on a link that adds 3 new transaction records to the transaction group.
  2. User sets different values in each of those three transaction records, each of which fires an onChange event that calls a JS function that needs to manipulate the DOM for each of the events in different ways. (Example: transaction 1 may be a return, so it changes the text of the transaction from cost to refund, transaction 2 may be for a service, so it changes the taxable status, etc...)
  3. The JS function has to be able to change the DOM for the correct transaction.

My problem is #3 - the DOM elements being modified are not the same as the element generating the event, so I can't use JS this. They are part of a common parent element (i.e. they share a parent <div>), so it may be possible for me to use jQuery parent/child selectors to navigate to the correct element in the DOM. However, even this requires some uniqueness in the div id attributes, and I'm not sure of the best way in Rails to dynamically generate these.

I suppose I could use random values, but this seems bad because it's not truly guaranteed to be unique and just seems like a hack. I suppose I could try to introduce some kind of counter,开发者_开发问答 but this seems to violate the principles of Rails development.

Any guidance is appreciated. Thanks!


Using the current time is recipe for pain and unexplained bugs. I highly recommend you use something like a GUID generator for generating unique IDs.


you could use Time.now as unique-id when creating a new tag

Time.now.to_i

it's not an hack or something that goes against Rails principles ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜