简体   繁体   English

未设置选择框的jQuery值

[英]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. 我正在使用AJAX根据选择的类别动态加载子类别。 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. 我认为也许,AJAX正在异步加载,并且在设置值时,实际上并未加载子类别。 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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