简体   繁体   English

如何使用javascript / jquery添加动态选项?

[英]How to add dynamic options using javascript/jquery?

I have a gsp page and on that have a ' <g:select> ' element as: 我有一个gsp页面,在该页面上有一个' <g:select> '元素为:

<label class="control-label">Applicable Offices:</label>
<span class="span6">
    <select name="data.OfficeId" class="required j-office-select" style="height:26px;padding:1px;">
        <option value="0">Select an office...</option>
    </select>
</span>

I have to add more "option" dynamically for this select using JavaScript. 我必须使用JavaScript为此选择动态添加更多的“选项” My JavaScript part looks like: 我的JavaScript部分如下所示:

$.ajax({
    url: epcm.urlManager.getUrl({controller: 'controllerName', action:'methodName'}),
    cache: false,
    contentType: "application/json",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(params),
    success: function(officeData) {
        var selectOffice = dialog.find('.j-office-select');
        selectOffice.empty();
        // OfficeData is a list . For each officeData , I need to add an option to the’ select’, but ways I tried did not work.I need to know the proper use of $.each and how can I use that in this context
        selectOffice.append('<option value="'+officeData.id+'">'+officeData.regionName+'</option>' );
        selectOffice.removeAttr('disabled');
        window.location.reload();
    }
});

"OfficeData", in the "success", is a list. “成功”中的“ OfficeData”是一个列表。 For each officeData , I need to add an option to the 'select' described above, but the ways I tried did not work. 对于每个officeData ,我都需要在上述“选择”中添加一个选项,但是我尝试的方法不起作用。 I need help with the proper use of $.each and how can I use that in this context. 我需要正确使用$.each以及在这种情况下如何使用它的帮助。 Can anyone help? 有人可以帮忙吗? The above example is adding only the first one, missing all others. 上面的示例仅添加了第一个,而忽略了所有其他。

Should be something like this: 应该是这样的:

$.each(officeData, function(index, item){
   selectOffice.append('<option value="'+item.id+'">'+item.regionName+'</option>' );
} );

However, in your example it does not seem like officeData is a collection since officeData.id and officeData.regionName are not nested inside items. 但是,在您的示例中,officeData似乎不是一个集合,因为officeData.id和officeData.regionName没有嵌套在项目内部。 You could use console.log(officeData); 您可以使用console.log(officeData); to output the data structure to your browser console (assuming you are using something like Chrome or FireFox+devtools). 将数据结构输出到浏览器控制台(假设您使用的是Chrome或FireFox + devtools之类的东西)。

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

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