如何使用rails对象在选择下拉列表中设置选项的值's的id

How to set the value of an option in a select dropdown using a rails object's id

本文关键字:id 选项 设置 对象 rails 何使用 选择 下拉列表      更新时间:2023-09-26

我在Rails中有一个模态,它构建了一个公司对象,将其返回到我的选择下拉列表中(使用正确的名称),对其进行预处理并自动选择。然而,数据库中的现有对象在列表中显示为Rails生成的选项,并带有选项的名称和一个值-这个值是它们的对象。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>

正如你所看到的,我没有正确的身份证。我做错了什么?

试试这个:

// 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>');