如何在选择另一个选项时更改 DDL 的 'selected' 属性并使用 jQuery 删除默认预选值

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

最初我需要在特定选项上设置“selected”属性,然后在 select 设置新选项时 remove/set 该属性。

1. 我最初可以通过以下方式将“selected”属性设置为特定选项:

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

2. 然后当我 select 一个新的选项“on change event”时,通过做:

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

我的问题是如何从旧选项中动态删除“selected”。他们目前每次我 select 另一个选项

时都会重复

非常感谢您的帮助。

我的完整代码

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?
  });

});

您可以简单地使用 [selected] 选择器和 remoteAttr 来定位选定的选项。

在将所选元素设置到另一个元素之前,您需要这样做,所以在这一行之前。

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>