1

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?

1 Answer 1

1

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'];
Sign up to request clarification or add additional context in comments.

3 Comments

I did it but if I alert(opts[val]) I get [object Object]. alert(opts[val][0]) and alert(opts[val][1]) are undefined
And that's normal behavior, as you also have hashes as nested values. And hash (in this case - javascript object) mapped on string is "[object Object]". You can access individual properties of each value as well. Try console.log(opts[val]) and you should see the proper output on browser's dev console (on chrome or ff). If you want opts[val] back as a string (json). Just do JSON.stringify(opts[val]), and you should get the json as the alert output.
I've updated the answer. No wonder you get opts[val][0] as undefined, as there's no such key in any of the hash values. Do opts[val]['col'] for example.

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.