Reputation: 521
I'm trying to retrieve the value of a f.select
form helper in my rails application.
The code for the f.select is (in HAML):
= f.select :level, [["L1 - Super easy", 1], ["L2 - Warm-up", 2], ["L3 - Easy exam questions", 3], ["L4 - Moderate exam questions", 4], ["L5 - Difficult exam questions", 5]], id: "level-AS"
which results in the following html:
<select id="test_level" name="test[level]">
<option value="1" selected="selected">L1 - Super easy</option>
<option value="2">L2 - Warm-up</option>
<option value="3">L3 - Easy exam questions</option>
<option value="4">L4 - Moderate exam questions</option>
<option value="5">L5 - Difficult exam questions</option>
</select>
The f.select has an id of "level-AS" and I have managed to target it using
$('#level-AS').select()
and that gives me Object { context: HTMLDocument → new, selector: "#level-AS" }
but what I want is for it to return the actual value that has been selected, i.e. "Easy" or "Hard".
I also tried
$('#level-AS').select().val()
and I have also tried
$('#level-AS').val()
but this returns undefined....
Upvotes: 2
Views: 1119
Reputation: 115511
You should simply do:
$('#level-AS').val()
Or according to your html:
$('#test_level').val()
Sidenote, instead of targeting by id, you could do:
$('select[name="test[level]"]').val()
Upvotes: 4
Reputation: 32933
I think your problem is that the ID in your f.select is getting lost. I think it's due to how rails is splitting up the arguments into the various sections. Try this:
= f.select :level, [["L1 - Super easy", 1], ["L2 - Warm-up", 2], ["L3 - Easy exam questions", 3], ["L4 - Moderate exam questions", 4], ["L5 - Difficult exam questions", 5]], {}, {id: "level-AS"}
Upvotes: 1