简体   繁体   English

设置选择选项的默认值

[英]Set default value of select option

I have a drop down select option like below 我有一个下拉选择选项,如下所示

<select id="find_best" name="finding_best">
    <option value="10">One</option>
    <option value="20">Two</option>
    <option value="30">Three</option>
</select>

This is inside a form and when the form is submitted and if there are validation errors, selected option disappear. 这在表单内,提交表单后,如果存在验证错误,则所选选项消失。 Say if I selected Three and then submit and if any validation error occur the page is reloaded and the option is not selected any more. 假设我选择了“三”然后提交,并且如果发生任何验证错误,那么将重新加载页面,并且不再选择该选项。 Use has to select it again. 使用必须再次选择它。

But I want to keep the selected option even after reloading the page after submiting the form. 但是即使提交表单后重新加载页面后,我也希望保留选择的选项。 I tried this 我试过了

 <% if defined?(params[:finding_best]) %>
        $("#find_best").val(<%= params[:finding_best] %>);
 <% end %> 

But this is not working. 但这是行不通的。 Let me how can I do this. 我该怎么做。

What you need to do, is add the selected attribute to the correct <option> element, so that the browser knows what was selected. 您需要做的是将selected属性添加到正确的<option>元素中,以便浏览器知道选择了什么。 Your final HTML should look something like this. 您的最终HTML应该看起来像这样。

<select id="find_best" name="finding_best">
    <option value="10">One</option>
    <option value="20">Two</option>
    <option value="30" selected>Three</option>
</select>

In rails you have to use rails helper functions. 在rails中,必须使用rails helper函数。 If you are using form_for then write it with form object f.select 如果使用form_for,则将其与表单对象f.select一起写入

If you are using simple form tag then try this: 如果您使用的是简单表单标签,请尝试以下操作:

<%= select_tag :find_best, raw(options_for_select([['One', 10],['Two', 20],['Three', 30]], params[:find_best])) %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM