Reputation: 629
I have a modal in Rails that builds a Company Object, returns it to my select dropdown (with the correct name), prepends it and auto-selects it. However the existing Objects from the database appear in the list as rails generated options, and carry both the name of the option as well as a value - this value being their object.id so I can associate two models together. I can't for the life of me work out how to write the javascript to update the value in the dropdown as well as it's text.
My current 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();
I have tried using:
<%= j @company.id %>
To retrieve the id, but that doesn't work. I've also tried all manned of attempts to get the value to automatically set (such as just trying to prepend the entire rails object to the form), with no luck.
The html generated by my current code:
<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>
As you can see, I don't have the right id being passed through. What am I doing wrong?
Upvotes: 0
Views: 3087
Reputation: 16002
Try this:
// 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>');
Upvotes: 1