pangpang
pangpang

Reputation: 8831

How to pass rails data to JS or Coffeescript?

I want to get the article id from view.

<%= f.text_area :content, rows: 5, placeholder: 'input....', class: 'form-control',
    id: "tags", data: {article_id: @article.id } %>

then pass the article_id to coffeescript:

$ ->
  id = $("#tags").data('article_id')
  console.log "test-----------#{id}"
  $("#tags").autocomplete(
    source:  '/articles/' + id + '/autocomplete.json')

but output is:

test-----------undefined

How to pass rails data to JS or coffeescript? How many ways to make it?

Thanks in advance!

as @muistooshort and @JoelL said: data: {article_id: @article.id} will produce data-article-id="xxxx"

html output:

<textarea rows="5" placeholder="input..." class="form-control" id="tags" data-article-id="{&quot;$oid&quot;:&quot;560017ddbd172d16d6000001&quot;}" name="comment[content]">

but I got the info from browser console log:

test----------[object Object]

it is not a string.

Upvotes: 0

Views: 348

Answers (3)

akbarbin
akbarbin

Reputation: 5105

Updated:

You can add manually in you input because of containing {} in your data-article-id:

<%= f.text_area :content, rows: 5, placeholder: 'input....', class: 'form-control', id: "tags", 'data-article-id': @article.id %>

For Jquery :

Try attr to get value attribute:

id = $("#tags").attr("data-article-id")
console.log "test-----------"+id

For coffeescript :

id = $("#tags").data("article-id")
console.log "test-----------"+id

Upvotes: 1

Joel
Joel

Reputation: 4603

data: {article_id: @article.id} will produce data-article-id="theid"

The following should work:

id = $("#tags").data('article-id')

Upvotes: 2

Prakash Laxkar
Prakash Laxkar

Reputation: 854

Try this

id = $("#tags").data('article_id')
console.log "test-----------"+id

Upvotes: -1

Related Questions