Search code examples
htmlruby-on-railshtml-selecterbhidden

How to have a select_tag with an "selected disabled hidden" option?


I want to have a select_tag that includes a field which displays "Please select" to the user. This field must not be selectable by the user.

Here is a jsfiddle of what I want to have : http://jsfiddle.net/gleezer/pm7cefvg/1/

In Rails, I tried to do this :

  <%= select_tag(:userchief, options_for_select(@options_for_selectUsers, {:selected => "x1", :disabled => "x1", :hidden => "x1"})) %>

(@options_for_user is an array which contains multiple key/value elements) But when I check the source code of my page, I can see this for my option :

<option disabled="disabled" selected="selected" value="x1">Select</option>

That is not what I want to have, the x1 select option appears in the dropdown menu of the select because the hidden field is not present.

How can I do to obtain the same result as I can see in the jsfiddle link ?


Solution

  • Use :prompt => "Placeholder" if you want the placeholder to show up only when the attribute is nil at the time the form is rendered. It will be selected by default, but nothing will be saved if user submits. If the attribute is already populated [possibly because a) there's a default value or b) it's an edit form], the placeholder item will be omitted from the list entirely.

    select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
    # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
    

    OR

    Use :include_blank => "Placeholder" if you want to include the placeholder in the rendered list at all times.

    Update

    Following code will disable the prompt after change. this is much similar to your example.

    <%=  select_tag(name = 'person', options_for_select(User.all.unshift("your prompt message"), selected: prompt, disabled: prompt,) ) %>
    

    And if you want to remove the prompt on select changes than you need to use jquery.

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