Reputation: 403
I have a following javascript code:
<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema%>' />
<script>
function select_pk2(cell){
var val = $('#query_form_opt_'+cell+'_1').val();
var opts = $('#query_form_select_ops').val();
}
</script>
Example:
schema
is a typical ruby hash:
{
"car"=>{"col"=>"blue", "engine"=>"HHd4M"},
"train"=>{"col"=>"black", "engine"=>"8495f"}
}
The variable val
has a value "train" and opts
the whole ruby hash
To access the col
and engine
of a train
in ruby: schema["train"]. How can I do the same in javascript?
I have tried:
var select = opts[val]
but it tells me that var in undefined. How can I access the values of a ruby hash in javascript given a hash and one of the keys?
Upvotes: 1
Views: 1202
Reputation: 163
Dump schema
hash as a json and then parse it back in javascript. Something like this:
<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema.to_json %>' />
And script:
function select_pk2(cell){
var val = $('#query_form_opt_'+cell+'_1').val();
var opts = JSON.parse($('#query_form_select_ops').val());
}
This way you should be able to access values in the way you want.
Each individual value of the hash in your example is hash as well, so you can access them by using proper keys. Like this:
opts['car']['col'];
Upvotes: 1