Reputation: 135
In my view, I have this form with the select function:
<form id="form_id">
<%= form.select('id','name', @document.informations.find(:all).collect {|u| [u.name] },
options={},{:onChange => 'submit()'}) -%>
</form>
How can I use the selected name in the rest of my view ?
I saw this in other topics:
$('#id_name').val();
But it didn't work for me, it says:
`$(' is not allowed as a global variable name
Upvotes: 0
Views: 1869
Reputation: 6072
You're getting that particular error because the $('#id_name').val()
is JavaScript, not Ruby, but you've put it within erb tags.
When you visit a page /documents/3
in your browser, Rails will run the code in your controller, and send back some HTML to your browser. That HTML can load CSS and JavaScript, but that's run after your Ruby program has finished - and may not be run at all, depending on the browser. How you use the name of the selected item in your view depends on what you're doing with it.
If you're storing it in the database somewhere, then you should start by getting this working just in Ruby. For instance, if your @document
has a selected_informations
attribute, you could use that in the rest of your page, and pass it to your form.select
to pre-select it in the page. The Rails Guides documentation has more info on this.
If you're not storing it in the database, then you can get the value of your box out with JavaScript whenever it changes. Here's some sample code that prints out the name of the selected item to the JavaScript console whenever a <select>
box gets changed. I've included it in <script>
tags so you can drop it straight into your view for testing, but you should put it into a dedicated JavaScript file if you adapt it for your project.
<script>
$('select').on('change', function(ev) {
var selected_item = $(ev.currentTarget).val();
console.log("Your select value is " + selected_item);
});
</script>
One final thing to note is that your existing form.select
tag is set up to call a method submit()
whenever its value gets changed. submit
is just a name, so that function could do anything... but I'd guess it's submitting the form whenever an item is selected. This sends a request to your Rails server and refreshes the page, so beware - if you're using an event listener on change
to update the current page, you won't see those changes on the new, refreshed page (and should use a server-side solution instead).
Upvotes: 2