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.

4
  • 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: stackoverflow.com/questions/16582901/… Commented Feb 11, 2016 at 22:10
  • Is there any particular reason you're not using a bunch of <input type="hidden" name="whatever[]"> to pass the array to Rails? That would give you an actually array inside params in Rails. Commented Feb 12, 2016 at 0: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.... :) Commented Feb 15, 2016 at 13:50
  • No, it isn't easier, quick hacks are rarely quick :) Using a bunch of individual <input type="hidden"> 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. Commented Feb 15, 2016 at 19:53

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

Comments

-1

Try using eval on your controller.

eval(params[:hidden_docs])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.