2016-01-20 264 views
0

我想删除HTML中的默认选定选项,并将第一个设置为选定,我的jQuery似乎设置第一个选项为选定的罚款,但它没有出现选择为它不是移除原始选择的选项出于某种原因...我试图2层的方法,其是如下: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'); 

从源头

<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> 

HTML你可以看到它走的是第一个选项,使得选择不删除初步设定这样一个它不改变为第一

不知道什么即时失踪....

谢谢

+0

你有没有尝试改变select'的'了'.VAL()',然后取下第一'option'? – Twisty

+0

不知道我需要更改值吗?只想删除选中的选项,然后将第一个选项设置为选中状态? – James

+0

我建议在整个过程中使用'prop()',并且不要使用'attr()',只是为了保持一致性。 –

回答

0

原来什么方法我在做什么是好的,但我需要在

$(window).load(function(){ 

看起来这个选项是在我试图设置它之后设置的

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(); 
}); 
0

你可以尝试这样的:

$(#elm_24).removeAttr('selected'); 
0
$('.ty-profile-field__select-state').val(''); 
$('.ty-profile-field__select-state option:first').prop('selected', true); 
$('.ty-profile-field__select-state option').each(function() { $(this).prop('selected', false); }); 
$(".ty-profile-field__select-state option:first").prop('selected', true); 
$('.ty-profile-field__select-state').find('option:selected').prop('selected', false); 
enter code here 
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