Bernd Strehl
Bernd Strehl

Reputation: 2920

Change the displayed select option with jquery

I've got following problem:

I'm calling a bootstrap modal with a form in it. The form comes with a dropdown and looks like following:

<select id="requirement_id" name="requirement_id">
    <option value="2">Sample     Requirement</option>
    <option value="3">Second Req</option>
    <option value="5">New Req</option>
</select>

I added a piece of jquery with adds selected="selected"to a specific option, which i want to be selected by default. When i submit the form, this option seems to be selected, but no matter which option gets selected by my script: The Text in the Select Field is always "Sample Requirement" (the first one)

Do you have an idea, how to change that? My jQuery Code is following:

$('.add_feature').click(function(){
    $('#requirement_id option').each(function(){
      $(this).removeAttr('selected');
    });
    $('#requirement_id').find('option[value="'+$(this).data('requirement')+'"]').attr('selected', 'selected');
  });

Upvotes: 3

Views: 4374

Answers (2)

Smern
Smern

Reputation: 19066

You are overthinking it, you don't need to remove or add a selected attribute on the option. All you need to do is use val() on the select and let jQuery do the work for you.

$('#requirement_id').val(valueOfOptionToSelect));

In your case it seems to be:

$('#requirement_id').val($(this).data('requirement'));

Assuming .add_feature has a data-requirement containing the value of the option to select (2, 3, or 5)

Fiddle

If you do want to do without val(), just change attr() to prop() in your code and the removeAttr() becomes unnecessary:

$('#requirement_id').find('option[value="' + $(this).data('requirement') + '"]').prop('selected', 'selected');

Fiddle

Upvotes: 5

speti43
speti43

Reputation: 3046

Try this:

$('#requirement_id').val($(this).data('requirement'));

Upvotes: 1

Related Questions