2011-09-10 58 views
0

我似乎無法得到這個工作,我找不到任何錯誤。這裏是選擇選項:Jquery #div選項:選定的問題

<select id="elecspend"> 
     <option selected="selected" value="month">Monthly Spend</option> 
     <option value="yearly">Yearly Spend</option> 
     <option value="quarterly">Quarterly Spend</option> 
     <option value="consumption">Yearly Consumption (kWh)</option> 
    </select> 
<div class="consumptext">Enter your monthly spend in here: </div> <input style="width: 80px;" type="text"> 

這裏是jQuery的。

$(document).ready(function() { 
$("#elecspend").change(function() { 


    if($("#elecspend option:selected").attr('value') == 'monthly') { 
     $(".consumptext").html("Please enter your monthly electricity spend"); 
    } 
}); 
}); 

感謝您的幫助球員。 Sam

+0

您尚未描述所需的功能。 –

回答

2

在您的選項中沒有「每月」的價值。我想你想要「月」,你可以使用this.value來獲得價值。嘗試改變這一點:

if($("#elecspend option:selected").attr('value') == 'monthly') 

這樣:

if (this.value == 'month') 

它在這裏工作:http://jsfiddle.net/jfriend00/tFvtb/

+0

attr('value')和val()之間的區別是什麼。哦,謝謝你的時間。 –

+0

'.attr(「value」)'在這種情況下可能正常工作,但如果您已經在使用jQuery,我認爲'.val()'更清潔,jQuery代碼中有一些跨瀏覽器的bug清理爲'.val()'。這兩種方式可能都不是什麼大不了的事。 – jfriend00

+0

我更簡單地使用'this.value'。 – jfriend00

0

您已將'monthly'與'month'混淆了。更改月份進入 '月月' 的值,然後使用此代碼:

$("#elecspend").change(alterPrompt); 

function alterPrompt() { 
    var selectedValue = $("#elecspend option:selected").attr('value'); 
    $(".consumptext").html("Please enter your "+ selectedValue +" electricity spend"); 
} 
alterPrompt(); 
+0

感謝Bernhard我會的。 –

0

你可以做的

if ($("#elecspend").val() == "month") 

代替

if($("#elecspend option:selected").attr('value') == 'monthly') 

見API文檔val。這是一個jsFiddle example

0

你不能使用this.value

在未來的尖端,你媒體鏈接發現#elecspend在你改變你可以使用:

$("option:selected", this) 

女巫是一個更快的選擇。