2016-01-20 267 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