简体   繁体   中英

JQuery Value of Select Box Not Being Set

I'm creating a page where a user of my website could edit a listing that they have created. There are three categories of listing, each with their own subcategories. I'm using AJAX to dynamically load the subcategories depending on what category is chosen. Being that this is an editing page, the values of each field must be preset so the user can change them if they wish to. The category loads fine, as do the subcategories. But, I'm having trouble setting the value of the subcategory select box to the listing's subcategory value.

Here is the function which loads the subcategories:

function loadEditSubcats(){
$('#edit-subcategory').empty();

var cat = $('#category-hidden').val();

var postData = { category : cat };

$.post("/assets/scripts/fetch_subcats.php",
        postData,
        function(data, text, jqxhr) {
            $.each(data, function(key, val){
                $('#edit-subcategory').append('<option value="' + val + '">' + val + '</option>');
            });
        },
        'json'
    ).fail(
        function( jqXHR, textStatus, errorThrown ) {
            alert(errorThrown);
        }
    );
}

This is where I load the subcategories when the page loads, as well as attempt to preset the subcategory's value:

$(document).ready(function () {
    loadEditSubcats();
    $("#edit-subcategory").val($('#subcat-hidden').val());
});

And finally, here's the select box for the subcategory, as well as the hidden value containing the initial subcategory:

<input type="hidden" id="subcat-hidden" value="<?=$item->subcategory?>">
<div class="form-group col-md-6">
    <label id="name-label"><h3>Subcategory</h3></label><br>
    <span "dropdown-menu-right">
        <select class="form-control" id="edit-subcategory"></select>
    </span>
</div>

I think that maybe, AJAX is loading asynchronously and by the time the value is being set, the subcategories aren't actually loaded. Any insight is greatly appreciated! Thank you!

you can change your approach like following to make this work

$.ajax({
type: "POST",
url: "/assets/scripts/fetch_subcats.php",
data: postData,
success: function(data){

  $.each(data, function(key, val){
            $('#edit-subcategory').append('<option value="' + val + '">' + val + '</option>');
        });

  //Do this in success function
  $("#edit-subcategory").val($('#subcat-hidden').val());

},
dataType: json
});

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