Reputation: 65
Among other things I am trying to alert the selected value in the 'Amount' drop down box which is a list of numbers from 1 to 10. The list is generated and then inserted in to a div.
// generate the amount dropdown list
var dropdown = "<select name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div></div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
My question is: Why does it produce 'undefined' when I alert the amount? I am expecting it to return the selected number
Upvotes: 1
Views: 3133
Reputation: 1172
The id
is missing on your dropdown.
// Generate the amount dropdown list
var dropdown = "<select id="amount" name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div>/div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
Upvotes: 0
Reputation: 83358
Make sure you give your select an id—right now it just has a name. As a result, your jQuery('#amount')
selector is not returning anything, which is why the alert is showing
undefined
.
var dropdown = "<select id='amount' name='amount'>";
Upvotes: 5
Reputation: 74738
use this if this works for you:
jQuery(document).ready(function() {
var amount = jQuery("select[name='amount']").val();
alert(amount);
});
Upvotes: 0
Reputation: 7663
you are using amount = jQuery("#amount").val();
for that you have to give your dropdown an id
var dropdown = "<select name=\"amount\" id=\"amount\">";
Upvotes: 3