简体   繁体   中英

Get value of select loaded with AJAX

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM