2013-05-21 22 views
0

我是一個新手與Jquery,我想追加一個選擇選項。這可以工作,當我選擇新添加的選項。我在alert中未定義。追加選擇選項並選擇附加選項警報顯示未定義+ Jquery

var selects = $(this).closest('div').find('.accSelectandlookup') ; 

//Check if the accid is already present in the selectoptions and if not then add 

if (!selects.find('option[value="' + accid + '"]').length) { 
alert(accid); // This throws up the correct value 
selects.append('<option value="' + accid + '">Attach to Existing : ' + accname + '</option>'); 
} 

我在做什麼錯?

在此先感謝

selects.change(function(){ 

alert('selected value is ' + selects.filter(":selected").val()); // This throws undefined 
}) 
+1

創建小提琴請 –

+0

控制檯中的日誌選擇,並確保您正確地得到select元素。 –

回答

1

只需使用$(this).val()來獲取當前select的選擇option值。當由於變量範圍觸發change事件時,selects可能不可用。

selects.change(function(){ 
    alert('selected value is ' + $(this).val()); // This throws undefined 
}); 
1

當您加載.change()函數時,它讀取當前的DOM。

當您使用append時,它會更改DOM,但不會更新.change()正在查看的內容。所以,你需要修改它是這樣的...

$('body').change(function(){ 
    alert('blah'); 
}, '.accSelectandlookup'); 

這使.change() LIVE,使用當前的DOM。