0

Here's what I'm doing in Coffeescript:

good_docs = []
  $('#documents_yes a').each (index) ->
  good_docs.push parseInt($(@).data('id'))

$('.hidden-docs').val(good_docs) #this is a hidden field

The problem is that the array is passed to my rails app as ["1, 2, 3"], but I need it to go in as [1, 2, 3].

How can I do this? I thought the parseInt call would handle it.

croceldon
  • 4,511
  • 11
  • 57
  • 92
  • 1
    The `parseInt` is doing exactly what you think, but then you're storing an array in an HTML input field. This will stringify your data. I suggest using a `select` input with the multiple attribute, and tinker with that. Look at this question for a little inspiration: http://stackoverflow.com/questions/16582901/javascript-jquery-set-values-selection-in-a-multiple-select – Brennan Feb 11 '16 at 22:10
  • Is there any particular reason you're not using a bunch of `` to pass the array to Rails? That would give you an actually array inside `params` in Rails. – mu is too short Feb 12 '16 at 00:43
  • @muistooshort - The number of `good_docs` will be variable. I thought it be easier to have one field to put them in rather than building a custom number of fields on the fly. Of course, it hasn't turned out to be easier.... :) – croceldon Feb 15 '16 at 13:50
  • No, it isn't easier, quick hacks are rarely quick :) Using a bunch of individual `` as above and manipulate those, you'll get a more natural interface and everyone will be happier. You can attach `class` attributes to the hidden inputs to make it easier to manipulate them or throw them all in container of some sort. – mu is too short Feb 15 '16 at 19:53

2 Answers2

2

You can't directly. Javascript is stringyfing the array, just like JSON. the easier route in my opinion is to grab that string and convert it into an array on the Rails side, with something like:

$('.hidden-docs').val(good_docs.join())

That gets you '1,2,3' in the hidden field. Now split and convert to numbers in Rails:

"1,2,3".split(',').map(&:to_i)

That will get you: [1, 2, 3]

Leonel Galán
  • 6,993
  • 2
  • 41
  • 60
-1

Try using eval on your controller.

eval(params[:hidden_docs])
Lymuel
  • 574
  • 3
  • 10