sam.tldr
sam.tldr

Reputation: 65

Using Jquery val() on a dropdown list

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

Answers (5)

Dilberted
Dilberted

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

Adam Rackis
Adam Rackis

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

Jai
Jai

Reputation: 74738

use this if this works for you:

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

Upvotes: 0

rahul
rahul

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\">";

DEMO

Upvotes: 3

xkeshav
xkeshav

Reputation: 54016

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

Upvotes: 0

Related Questions