2014-01-18 22 views
1

我正在開發一個Woocommerce(WordPress)項目,我的任務是在用戶單擊按鈕時從下拉列表中獲取選定值。jQuery從selectbox中得到選定的值不起作用

我的HTML是:

<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy"> 
    <option value="">Custom product attribute</option> 
    <option value="pa_bedroom">Bedroom</option> 
    <option value="pa_bathroom">Bathroom</option> 
</select> 

<button type="button" class="button button-primary add_attribute">Add</button> 

和jQuery代碼:

$('.add_attribute').on('click', function() { 
    var selected = $('#attribute_taxonomy option:selected'); 
    alert(selected.val()); 
}); 

不幸的是我得到的空白警告框,沒有得到任何東西。但奇怪的是,當我創建jsFiddle與相同的HTML & jQuery代碼我得到正確的輸出。

爲什麼我沒有得到任何東西。有沒有其他解決方案?我對jQuery不太好,所以如果有人指導我解決這個問題,我會感激不盡。

我的樣本>JSFIDDLE

感謝。

+0

這是怎麼回事呢?你是否至少獲得了警戒?你是否動態加載你的頁面(通過ajax)? – Krishna

+0

檢查您的開發者控制檯(或螢火蟲控制檯)的任何錯誤! – Saurabh

+0

@克里希納是的,我得到警報框,但沒有得到價值。只需空彈出。不,我不使用ajax。 – lumos

回答

1

只需使用:

var selected = $('#attribute_taxonomy'); 
alert(selected.val()); 
1

你需要得到select元素,而不是它的選擇option的價值:

$('.add_attribute').on('click', function() { 
    var selected = $('#attribute_taxonomy'); 
    alert(selected.val()); 
}); 

JS Fiddle demo

我還趨於防止用戶與交互button直到選擇在select元件(使用disabled(布爾)屬性)和然後製成,一旦作出選擇,防止來自用戶重新選擇看起來像是option標籤的標籤(注意這比標籤更復雜,可能會有改進的方法)。首先,HTML:

<!-- select element unchanged --> 

<button type="button" class="button button-primary add_attribute" disabled>Add</button> 

的jQuery:

$('#attribute_taxonomy').on('change', function(){ 
    // cache the $(this) jQuery object since we're potentially using it twice: 
    var $this = $(this); 
    // if there are no disabled options we run the following jQuery: 
    if (!$this.find('option:disabled').length) { 
     $this 
     // find the option that has no value set: 
     .find('option[value=""]') 
     // set its 'disabled' property to true (to disable it) 
     .prop('disabled', true) 
     // go back to the original selector ($(this)) 
     .end() 
     // move to the next element (if it's a button element): 
     .next() 
     // unset its 'disabled' property (to enable it): 
     .prop('disabled',false); 
    } 
}); 
$('.add_attribute').on('click', function() { 
    var selected = $('#attribute_taxonomy'); 
    alert(selected.val()); 
}); 

JS Fiddle demo

稍微好一點的方法(在我看來)是正確使用HTML及其元素;使用optgroup到相關option元件相關聯,以label屬性設置爲解釋該組中的內容:

<select name="attribute_taxonomy" id="attribute_taxonomy" class="attribute_taxonomy"> 
    <optgroup label="Custom product attribute"> 
    <option value="pa_bedroom">Bedroom</option> 
    <option value="pa_bathroom">Bathroom</option> 
    </optgroup> 
</select> 

JS Fiddle demo

這種方法意味着一種選擇,具有價值,始終設置(雖然最初的默認除非這些option S的一個被賦予了selected屬性),這意味着button並不需要有其disabled財產設置/取消設置以防止無意中選擇無值的option

參考文獻: