选择不删除的jQuery删除集选择选项

时间:2016-01-20 00:35:46

标签: javascript jquery html

我正在尝试删除HTML中的默认选定选项,并将第一个选项设置为选中,我的jQuery似乎将第一个选项设置为选中,但它没有显示为选中,因为它不是删除原始选定的选项。我尝试了以下两种方法:

选项1

$('.ty-profile-field__select-state :selected').prop('selected', false);
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

选项2

$('.ty-profile-field__select-state option').each(
    function() {
        $(this).removeAttr('selected');
    }
);
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

选项3

$('.ty-profile-field__select-state').find('option:selected').removeAttr("selected");
// mark the first option as selected
$(".ty-profile-field__select-state option:first").attr('selected','selected');

源自HTML

<select x-autocompletetype="state" id="elm_24" class="ty-profile-field__select-state cm-state cm-location-billing" name="user_data[b_state]">
    <option value="" selected="selected">- Select state -</option>
    <option value="ACT">Australian Capital Territory</option>
    <option value="NSW">New South Wales</option>
    <option value="NT">Northern Territory</option>
    <option value="QLD">Queensland</option>
    <option value="SA">South Australia</option>
    <option value="TAS">Tasmania</option>
    <option value="VIC" selected="">Victoria</option>
    <option value="WA">Western Australia</option>
</select>

您可以看到它选择了第一个选项并选择不删除最初设置的选项,因此它不会更改为第一个选项。

5 个答案:

答案 0 :(得分:0)

不确定,但是您说要删除默认值,将下一个项目保留为所选项目。这样做:https://jsfiddle.net/Twisty/um7xhx7m/1/

$(document).ready(function() {
  $('.ty-profile-field__select-state option:selected').remove();
});

现在,如果此页面加载时其他内容为:selected,则会将其删除。因此,您可以调整为仅选择option[0],如此:

$(document).ready(function() {
  $('.ty-profile-field__select-state option:eq(0)').remove();
});

答案 1 :(得分:0)

你可以尝试类似的东西:

$(#elm_24).removeAttr('selected');

答案 2 :(得分:0)

clear

答案 3 :(得分:0)

原来我正在做什么方法很好,但我需要包装

$(window).load(function(){

似乎在我试图设置它之后正在设置选项

答案 4 :(得分:0)

你可以这样做。

    $(document).ready(function(){

      $(".ty-profile-field__select-state option").removeAttr('selected');

      $(".ty-profile-field__select-state option:nth-child(2)").attr('selected',true);//Australian Capital Territory

      $(".ty-profile-field__select-state option:first").attr('selected',true);//Select state 

    })

以下是plunker

当您说option:first时,它是Select state

的第一个孩子
相关问题