1

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

1
  • 3
    It alerts undefined because an element with ID amount does not exist. Commented Nov 19, 2012 at 5:08

5 Answers 5

5

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'>";
Sign up to request clarification or add additional context in comments.

5 Comments

The value attribute is not needed though.
@Felix - with no value .val() will by default return the text of the selected option?
@AdamRackis value attribute not needed it's working fine without this also here jsfiddle.net/wdtkf
Yes, that's actually just how the DOM interface works (i.e. it's not a jQuery feature).
3

you are using amount = jQuery("#amount").val(); for that you have to give your dropdown an id

var dropdown = "<select name=\"amount\" id=\"amount\">";

DEMO

Comments

0

there are 2-3 Approach to get a selected value from <select>

1 Comment

Nothing! but above are just made for this kind of purpose. .val is parent at all :)
0

use this if this works for you:

 jQuery(document).ready(function() {
   var amount = jQuery("select[name='amount']").val();
    alert(amount);
});

Comments

0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.