我在Rails中有一个模态,用于构建公司对象,将其返回到我的选择下拉列表(具有正确的名称),预先设置并自动选择它。但是,数据库中的现有对象在列表中显示为rails生成的选项,并且同时包含选项的名称和值 - 该值是它们的object.id,因此我可以将两个模型关联在一起。我不能为我的生活找出如何编写javascript来更新下拉列表中的值以及它的文本。
我目前的jquery:
//close the modal
$('#competitor_modal').modal('hide');
//prepend the name of the company to the select dropdown
$('#sales_opportunity_company_id').prepend($('<option></option>', {
text: <%= j @company.company_name%>,
}));
//select the newly prepended option
$('#sales_opportunity_company_id>option:eq(0)').attr('selected', true);
//show the submit button (I hide it whilst they are creating a new company to stop them accidentally submitting with the value "add new company"
$('#submit').show();
我尝试过使用:
<%= j @company.id %>
要检索ID,但这不起作用。我也试过所有有人试图让值自动设置(例如只是试图将整个rails对象添加到表单中),没有运气。
我当前代码生成的html:
<select id="sales_opportunity_company_id" name="sales_opportunity[company_id]">
<option selected="selected">2</option>
<option value="1">Any company</option>
<option>Add new company</option>
</select>
正如您所看到的,我没有正确的ID被传递。我做错了什么?
答案 0 :(得分:1)
试试这个:
// remove previously selected value:
$("#sales_opportunity_company_id :selected").removeAttr("selected");
// add new option as selected value:
$("#sales_opportunity_company_id").prepend('<option selected="selected" value="<%= @company.id %>"><%= @company.company_name %></option>');