Jquery #div option:selected problem
I can't seem to get this to work and I can't find any mistakes. Here is the select options:
<select id="elecspend">
<option selected="selected" value="month">Monthly Spend</option>
<option value="yearly">Yearly Spend</option>
开发者_如何学Python <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">
Here is the jquery.
$(document).ready(function() {
$("#elecspend").change(function() {
if($("#elecspend option:selected").attr('value') == 'monthly') {
$(".consumptext").html("Please enter your monthly electricity spend");
}
});
});
Thanks for your help guys. Sam
There's no value "monthly" in your options. I think you want "month" and you can use this.value
to get the value. Try changing this:
if($("#elecspend option:selected").attr('value') == 'monthly')
to this:
if (this.value == 'month')
It's working here: http://jsfiddle.net/jfriend00/tFvtb/.
You've confused 'monthly' with 'month'. Change the value of the Month entry to 'monthly' and then use this code:
$("#elecspend").change(alterPrompt);
function alterPrompt() {
var selectedValue = $("#elecspend option:selected").attr('value');
$(".consumptext").html("Please enter your "+ selectedValue +" electricity spend");
}
alterPrompt();
cant you just use this.value
?
A tip in the future, you allready have found #elecspend in your change you can just use:
$("option:selected", this)
witch is a faster option.
You can do
if ($("#elecspend").val() == "month")
instead of
if($("#elecspend option:selected").attr('value') == 'monthly')
See the API documentation for val. Here is a jsFiddle example.
精彩评论