0

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.

ctd25
  • 730
  • 1
  • 11
  • 22
  • Where's the js of your ajax call? If you're loading the select markup via AJAX, your function in document ready will never know it existed. – cport1 Jan 07 '15 at 21:47
  • 1
    jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use [event delegation](http://learn.jquery.com/events/event-delegation/), bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use `document` as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally [you should delegate to the nearest parent that exists at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Jan 07 '15 at 21:48
  • Thank you for the detailed answer - still new to jQuery and I appreciate it – ctd25 Jan 08 '15 at 13:13

2 Answers2

2

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.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
0

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.