Search code examples
javascripthtmljquerydropdown

How to change the 'selected' attribute of the DDL when selecting another option and remove the default preselected value with jQuery


Initially i need to set the "selected" attribute on a specific option and then remove/set the attribute when selecting a new option.

1. I can set initially the "selected" attribute to a specific option by doing:

$('select#genres option[value="0"]').attr("selected", "selected");

2. And then again when I select a new option "on change event" by doing:

$('select#genres').on('change', function () {
var newSelected = $('select#genres').find(":selected").attr("selected", "selected");
});

My problem is how to remove "selected" from the old options dynamically. They currently duplicate each time I select another option

Thank you so much for the help.

My complete code

HTML

<select id="genres">
       <!-- Preset option that i want -->
       <option value="0">All</option>

       <!-- Dynamically "selected" attribute on change and remove the Preset-->
       foreach (GenreViewModel genre in Model.Genres){
               <option value="@genre.Id" >@genre.Type</option>
       <!-- Output  
       <option value="1" >Action</option>
       and following option result... -->
       }
</select>

jQuery

$(document).ready(function () {

  //Preset option which has "value 0"
  $('select#genres option[value="0"]').attr("selected", "selected");


  $('select#genres').on('change', function () {
    //Add attribute to the new selected option
    var newSelected = $('select#genres').find(":selected").attr("selected", "selected");

   //Hot to remove the old "selected" attribute?
  });

});

Solution

  • You can simply target selected options using the [selected] selector and remoteAttr.

    And you will want to do that BEFORE you set the selected on another element, so BEFORE this line.

    var newSelected = $('select#genres').find(":selected").attr("selected", "selected");
    

    $('select#genres option[selected]').removeAttr("selected");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="genres">
      <option></option>
      <option selected>SELECED</option>
    </select>