2

I've got some coffee script in /assets/javascripts/transactions.coffee that populates a text field (in /views/transactions/_form.html.erb) with today's date in dd/mm/yy format.

$ ->
    today = new Date
    dd = today.getDate()
    mm = today.getMonth() + 1
    #January is 0!
    yyyy = today.getFullYear()
    if dd < 10
      dd = '0' + dd
    if mm < 10
      mm = '0' + mm
    today = dd + '/' + mm + '/' + yyyy
    $('#transaction_date').val today

$ ->
    $('#transaction_date').datepicker({dateFormat: "dd/mm/yy"})

Currently, that form is referenced in /views/transactions/new.html.erb and /views/transactions/edit.html.erb. However, I only want the text field to be populated on new.html.erb and not edit.html.erb.

What's the 'cleanest' way to achieve this in Rails (4.2.5)?

Bhav
  • 1,957
  • 7
  • 33
  • 66
  • Possible duplicate of [Best way to add page specific javascript in a Rails 3 app?](http://stackoverflow.com/questions/3437585/best-way-to-add-page-specific-javascript-in-a-rails-3-app) – Jen Nov 15 '16 at 21:18
  • @guiniveretoo I've added the version number (4.2.5). I'm hoping there's a better way to achieve this. – Bhav Nov 15 '16 at 21:24
  • there are 9 answers on that duplicate question. Have you tried all of them? What qualifies a new solution as being better? Edit your question to clarify why those solutions aren't acceptable or why your question isn't a duplicate. – Jen Nov 15 '16 at 21:29

1 Answers1

0

Maybe you can create functions in transactions.coffee that you call from your view with an inline script. For example, in transactions.coffee

this.App || (this.App = {})
this.App.Transactions =
    runForNewView: () ->
        today = new Date
        dd = today.getDate()
        mm = today.getMonth() + 1
        #January is 0!
        yyyy = today.getFullYear()
        if dd < 10
          dd = '0' + dd
        if mm < 10
          mm = '0' + mm
        today = dd + '/' + mm + '/' + yyyy
        $('#transaction_date').val today

Then for example in the new view template, you would just add

<script text="text/javascript">
    $(function() { App.Transactions.runForNewView(); });
</script>
atsui
  • 1,008
  • 10
  • 17