Search code examples
ruby-on-railsrubyruby-on-rails-3form-helpershtml-select

How to have a default select value that is NOT an option in drop down, using Ruby form select helper method


Ok so I am working on a project that was outsourced and now I get to jump in and fix everything before it gets pushed to production. I am currently trying to modify a line that creates a select form field. I read up on some of the different form helper methods to use in ruby, and over some of the available options for the method.

My problem is I can't seem to figure out how to get a default value to be displayed inside the select element without having it show up in the drop down options. This is what the line currently looks like.

<%= select :profile, :sexual_interest, SEXUAL_INTEREST_ARRAY, {:prompt => 'sexuality'}, {:class => 'selectFull'} %>

I tried changing some of the options using :default => 'sexuality' and then tried :disabled => 'sexuality'. But I seem to only be able to remove the option entirely from the select element or have it as the first value in the drop down list and being displayed as the default value.

If you are just having issues setting the default value of your select field using a ruby form helper, reference this post selecting a default for option field

If any one could give me some insight as to how to fix this issue I would greatly appreciate it. Any ideas would help, Thanks for reading.

-Alan


Solution

  • It is not possible to do that in HTML, so you'll have to use another approach.

    Possible solution

    Suppose you have:

    <select name="selectBox" id="selectBox">
        <option value="default">default</option>
        <option value="option1">option1</option>
        <option value="option2">option2</option>
        <option value="option3">option3</option>
        <option value="option4">option4</option>    
    </select>
    

    Then your javascript will looklike this:

    $("#selectBox").change(function(){
       $("#selectBox option[value='default']").remove();
    }​);
    

    The example on jsFiddle

    Selectors

    $('#selectBox option[value="SEL1"]')
    

    For an index:

    $('#selectBox  option:eq(1)')
    

    For a known text:

    $('#selectBox option:contains("Selection 1")')
    

    Hope it helps you!