Skip to main content

Use coffeescript or javascript in rails form to grab model attribute

Javascript • Asked by shakycode

I am working on a Rails app and need some help with coffeescript which I'm honestly not very good at.

I have a form with a field called location_id using a collection in Rails.

<%= f.grouped_collection_select :location_id, Region.order(:area), :active_locations, :area, :id, :location_name_with_address, {include_blank: true}, class: 'select' %>

On the Location model there is a column named modifier which holds a value. Within my form I need to be able to grab the modifier value to evaluate it client-side to display/hide a div.

I'm starting to write my coffeescript and am able to get the id of the Location like this

$('#run_location_id').val()

But what I'm unsure of how to do is, how do I grab that id of the location, and evaluate the model attribute modifier? I'm not sure how to grab it on the client side.

I've googled and have read a lot of coffeescript snippets but can't seem to find the right direction to take.

I just need a bump in the right path so I can figure the rest out on my own.


Hello,

Output your modifier value to a hidden text field and grab it with jQuery and do the logic to display the form field or hide it. You can just include a normal JS file rather than learn CoffeeScript (I personally prefer normal JS). Simply rename the file to .js.


Thanks for chiming in, Erik. The problem is the modifier is an attribute/column of the Location model and when selected it changes (it's not pre-loaded in the controller). I'm able to make it a data-attribute in the grouped select statement like this:

 <%= f.select :location_id, grouped_options_for_select(Region.order(:area).map{ |group| [group.area, group.locations.order('location_name asc').map{ |f| [f.location_name, f.id, {'data-modifier'=>f.location_modifier}] } ] }, {:include_blank => true, :class => 'select'}) %>

When I inspect via Chrome I see the data attribute of the selected location being set, but I'm unsure as to how to grab it from the html to evaluate it.

Thanks in advance for your help!


Oh, easy!

This should get you the data attribute value:

$('select#location_id').data('modifier');

You'll want to look into the jQuery .change method too to watch for changes on the select tag.


Thanks, that's getting closer to what I need. Problem is when I inspect the element and call $('select#location_id').data('modifier'); I get an undefined method in the console even though the location_id is selected in the form. If I do a $('select#location_id').data it give me this:

(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i+…

Clearly I don't understand JS very well, so I'm not sure what I'm missing but I sure do appreciate your help.


Post the select element that the server outputs here. We can get this working. :)


Sorry if this is a newb question me being seveal years in, but I'm assuming you want the element outputted in the console when I use Chrome's inspector. If so, it's going to be gigantic. Is there a certain way you want me to get this? Totally embarassing, but today I'm eating humble pie :)


No problem, and, yes the output of the code in Chrome inspector.

You can just post the parent select and one of the option tags. I just need to see what it's outputting to get you on the right track with the JS.


Cool, here's what I have so far. I should have been more clear that my selector id is prefixed with run. I apologize for not being more clear.

parentElement :select#run_location_id

option
accessKey
:
""
assignedSlot
:
null
attributes
:
NamedNodeMap
baseURI
:
"http://loopify.xyz:9001/runs/new"
childElementCount
:
0
childNodes
:
NodeList[1]
children
:
HTMLCollection[0]
classList
:
DOMTokenList[0]
className
:
""
clientHeight
:
0
clientLeft
:
0
clientTop
:
0
clientWidth
:
0
contentEditable
:
"inherit"
dataset
:
DOMStringMap
defaultSelected
:
false
dir
:
""
disabled
:
false
draggable
:
false
firstChild
:
text
firstElementChild
:
null
form
:
form#new_run.new_run
hidden
:
false
id
:
""
index
:
1
innerHTML
:
"Brookside Nursing Center"
innerText
:
"Brookside Nursing Center"
isConnected
:
true
isContentEditable
:
false
label
:
"Brookside Nursing Center"
lang
:
""
lastChild
:
text
lastElementChild
:
null
localName
:
"option"
namespaceURI
:
"http://www.w3.org/1999/xhtml"
nextElementSibling
:
option
nextSibling
:
text
nodeName
:
"OPTION"
nodeType
:
1
nodeValue
:
null
offsetHeight
:
0
offsetLeft
:
0
offsetParent
:
null
offsetTop
:
0
offsetWidth
:
0
onabort
:
null
onbeforecopy
:
null
onbeforecut
:
null
onbeforepaste
:
null
onblur
:
null
oncancel
:
null
oncanplay
:
null
oncanplaythrough
:
null
onchange
:
null
onclick
:
null
onclose
:
null
oncontextmenu
:
null
oncopy
:
null
oncuechange
:
null
oncut
:
null
ondblclick
:
null
ondrag
:
null
ondragend
:
null
ondragenter
:
null
ondragleave
:
null
ondragover
:
null
ondragstart
:
null
ondrop
:
null
ondurationchange
:
null
onemptied
:
null
onended
:
null
onerror
:
null
onfocus
:
null
oninput
:
null
oninvalid
:
null
onkeydown
:
null
onkeypress
:
null
onkeyup
:
null
onload
:
null
onloadeddata
:
null
onloadedmetadata
:
null
onloadstart
:
null
onmousedown
:
null
onmouseenter
:
null
onmouseleave
:
null
onmousemove
:
null
onmouseout
:
null
onmouseover
:
null
onmouseup
:
null
onmousewheel
:
null
onpaste
:
null
onpause
:
null
onplay
:
null
onplaying
:
null
onprogress
:
null
onratechange
:
null
onreset
:
null
onresize
:
null
onscroll
:
null
onsearch
:
null
onseeked
:
null
onseeking
:
null
onselect
:
null
onselectstart
:
null
onshow
:
null
onstalled
:
null
onsubmit
:
null
onsuspend
:
null
ontimeupdate
:
null
ontoggle
:
null
onvolumechange
:
null
onwaiting
:
null
onwebkitfullscreenchange
:
null
onwebkitfullscreenerror
:
null
onwheel
:
null
outerHTML
:
"<option value="1757" data-modifier="OT">Brookside Nursing Center</option>"
outerText
:
"Brookside Nursing Center"
ownerDocument
:
document
parentElement
:
select#run_location_id
parentNode
:
select#run_location_id
prefix
:
null
previousElementSibling
:
option
previousSibling
:
option
scrollHeight
:
0
scrollLeft
:
0
scrollTop
:
0
scrollWidth
:
0
selected
:
true
shadowRoot
:
null
slot
:
""
spellcheck
:
true
style
:
CSSStyleDeclaration
tabIndex
:
-1
tagName
:
"OPTION"
text
:
"Brookside Nursing Center"
textContent
:
"Brookside Nursing Center"
title
:
""
translate
:
true
value
:
"1757"
webkitdropzone
:
""

You are close! looking at the above the 'dataset' is empty which means your jquery targeting is slightly off.

I am assuming you want the value of modifier for the location that is the selected .

$('select#location_id :selected').data('modifier');

if you look this in the console:

$('select#location_id :selected')

the dataset shouldn't be empty and you should see modifier listed.

hope that helps.


Hey John, thanks for chiming in on this thread. You're right, I wasn't targeting the selected object. Doing $('select#location_id :selected').data('modifier'); gave me an output of the modifer in the console. I think I can take it from here and use the .change method to watch for the element changing then do some nifty logic to conditionally show/hide/populate my div.

Also thanks to Erik for helping me. You both are great, glad to have you onboard at Gorails. I love it when a community comes together and helps eachother out.

If you ever need a hand with anything ruby/rails I'm not a guru but I'd be happy to help :)


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.