使用jQuery Ajax在s:select中设置值 [英] Setting values in s:select using jquery ajax

查看:80
本文介绍了使用jQuery Ajax在s:select中设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用ajax调用来重置页面上的值. 我正在使用Jquery执行此操作.

I have to reset the values on a page using an ajax call. I am using Jquery to perform this.

必须在多选列表中重置值.

The values have to be reseted in a multi-select list.

如果我在选择框中更改值并单击重置",则必须在列表中设置数据库中最后保存的值.

If I change the value in the select box and click on reset then the last saved values from DB have to be set in the list.

我正在尝试以下

            function resetNameDetails() {

                            $.ajax({
                                            type: "POST",
                                            url: 'resetNameDetailsAction.action?,
                                            error: function(data) {
                                                            alert("error");
                                            },
                                            success: function(data) {

                                                            alert("sucess");
                                                            alert(data.userModel.nameList);

                                            }
                            });

            }

第二个成功的警报仅给出对象列表.我如何将这些数据传输到选择控件.

The second alert in success gives a list of Objects only. How I transfer this data to the select control.

更新

var nameListData = data.userModel.nameList; 
var select = document.getElementById('nameList'); 
alert(select); 
select.options.length = 0; // clear out existing items 
for(var i=0; i < nameListData.length; i++) { 
  var d = nameListData[i]; 
  alert(d); 
  select.options.add(new Option(d, i)) 
} 

向我显示了填充有[对象对象]的列表

shows me the list populated with [Object object]

推荐答案

假设data.userModel.nameList是值数组,则可以执行以下操作:

Assuming data.userModel.nameList is an array of values, you can do this:

...
success: function(data) {
   var values = data.userModel.nameList;
   $(":checkbox").each(function(){
      var value = $(this).attr("value");
      if($.inArray(value, values))
          $(this).attr("checked", true);
      else
          $(this).attr("checked", false);
   });    
}
...

编辑:用于复选框列表.对于多选,请执行以下操作:

EDIT: That was for checkboxes list. For a multi-select, do this:

...
    success: function(data) {
       var values = data.userModel.nameList;
       $("#your_select option").each(function(){
          var value = $(this).attr("value");
          if($.inArray(value, values))
              $(this).attr("selected", true);
          else
              $(this).attr("selected", false);
       });    
    }
...

希望这会有所帮助.干杯

Hope this helps. Cheers

这篇关于使用jQuery Ajax在s:select中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆