Form input ids for dropdown for rails/ jquery

I’m having difficulty identifying the input id for some rails form dropdown elements for a few jquery validations I want to perform client side. I was easily able to pickout the text field ids, but these dropdown fields are tricky.

Any suggestions? Can I pick out the id from the form element before it’s rendered on the front end?

If your form comes in as f, here’s a trick to get a <select>'s id:

<%= f.select :my_dropdown, options %>
<br>
The ID is <%= f.field_id(:my_dropdown) %>
<script>
  var mySelect = $(document.getElementById(<%= f.field_id(:my_dropdown) %>));
</script>
<br>
The name is <%= f.field_name(:my_dropdown) %>

Now in jQuery you can just reference mySelect and it’s a jQuery-enabled client-side object.

this is what one of my form dropdown controls look like…

<%= render partial: ‘form_controls/select’, locals: { f: f, label: Bag.human_attribute_name(“sorted”), property: :sorted, object: @bag, options: {include_blank: true}, collection: [[“Yes”, true],[“No”, false]] } %>

Making an assumption here not knowing what’s inside of form_controls/_select.erb, but you just might be able to get a jQuery reference to the <select> like this:

<script>
  var mySelect = $(document.getElementById(<%= f.field_id(:sorted) %>));
</script>