Reputation: 760
I am loading a select via AJAX and then trying to use the value of the select for another AJAX call.
So I have:
<select id ="thisSelect">
<option value = "someValue1"> Some Value 1 </option>
<option value = "someValue2"> Some Value 2 </option>
</select>
This loads fine. Then I am trying to access the value of thisSelect like so:
$(document).ready(function(){
var value = $('#thisSelect').val();
alert(value);
});
It only registers the first value that the select loaded with in the original AJAX call and isn't capturing any of the changes.
Any ideas? I tried:
$('#thisSelect').on('change', function() {
var value = (this.value);
//or
alert(this.value);
});
in the same $(document).ready block, but 'value' shows up as undefined and I don't get an alert box.
Upvotes: 0
Views: 4004
Reputation:
You could try
var array = [];
var i = 0;
$("#thisSelect").children().each(function () { array [i++] = $(this).val; });
It'll throw the values into an array you could then access.
Upvotes: 0
Reputation: 93551
It sounds like your content is loaded after the on change
statements are run.
Use a delegated event handler for the change instead:
$(document).on('change', '#thisSelect', function() {
var value = $(this).val();
alert(value);
});
This works by listening for the event to bubble up to a non-changing ancestor element (document is the default if nothing is closer). It then applies the jQuery selector at event time, so the item only has to match then.
Upvotes: 2