0

I have a simple Sinatra app that you can use to record the beers you drank on a certain night, their quantity, and type. To edit one of these user-entered nights I have a simple form that reflects the values that were entered when the drinking event was created:

<input type="text" value="<%= @beer.name %>" name="name"/>
<input type="text" value="<%= @beer.price %>" name="price"/>

So that's all well and good to have the value be populated from the database value. Now, how do I select the value for dropdown?

<select name="night">
    <option value="Monday">Monday</option>
    <option value="Tuesday">Tuesday</option>
    <option value="Wednesday">Wednesday</option>
    <option value="Thursday">Thursday</option>
    <option value="Friday">Friday</option>
    <option value="Saturday">Saturday</option>
    <option value="Sunday">Sunday</option>
  </select> 

I found I could do it using inline jquery:

<script>
$(document).ready(function(){
$(".edit select[name=type] option").each(function(){
if ($(this).val() == "<%= @beer.type %>"){
  $(this).attr("selected", true );
}
});
$(".edit select[name=night] option").each(function(){
if ($(this).val() == "<%= @beer.night %>"){
  $(this).attr("selected", true );
}
});
});
</script> 

But I don't really want to have to resort to inline js. Any suggestions?

2 Answers 2

1

I would do something like this

<select name="night">
  <% ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].each do |day| %>
    <option <%= 'selected="selected"' if day == @beer.night %> value="<%= day %>"><%= day %></option>
  <% end %>
</select>
Sign up to request clarification or add additional context in comments.

Comments

0

You may want to start with simple id selector for the select drop down box, like this:

<select id="day">...</select>

Then create an external javascript file, call it whatever you like such as day_select_handler.js  and include it in your view.

<html>
<head>
  <script type="text/javascript" src="day_select_handler.js"></script>
</head>
...

That way, the javascript file will be loaded when this page loads. And it is not inline and can be re-used in other pages as well.

2 Comments

The javascript has ruby instance variables in it, so putting it in a js file doesn't work
I would say put the instance variables in your view using data-attributes. And then in your javascript just retrieve the data-attributes using $('#something').data('beer_type')

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.