如何设置 select 选项的值

How to set the value of select option

我正在尝试根据第一个菜单的选择来填充下拉菜单。使用下面的代码只会使下一个下拉列表为空

  $(\".category_id\").change(function(){

    $(\"#account_id > option\").remove();
    $(\"#item_name_id > option\").remove();

    var  category_id={'category_id':$(this).val()};

 $.ajax({
       type: \"POST\",
       url: 'getCategory1/', 
       dataType: \"json\",
       data: category_id,
       success: function(category_ids){ 

 // category_ids = {"0":"Choose Account Name","2":"OfficeEquipment","3":"IT Equipment"}
               $.each(category_ids,function(account_id,name){

                  var opt = $('<option />');           
                  opt.val(account_id);
                  opt.text(name);

                  $(this).closest('td').next().find('select').append(opt);

             });
          }

      });
});

我使用的控制器功能:

  public function actionGetCategory1(){
        //Get all the sub categories a the main category
        $cat_id = $_POST['category_id'];
        $subCategory = Item::model()->getCategory1($cat_id); 
        echo(json_encode($subCategory));
    }

模型函数

public function getCategory1($cat_id){
        $where  = "WHERE category_id = $cat_id";
        $select = "SELECT * FROM tbl_account $where";
        $query  =  Yii::app()->db->createCommand($select)->queryAll();

        $subCat = array();
        $subCat[0] = "Choose Account Name";
           if($query){
              foreach($query as $row){
                $subCat[$row['account_id']] = $row['account_name'];
              }
              return $subCat;
            }
            else{ return FALSE; }
    }

要在 $.each 中循环的数据将以 json 格式来自控制器。我用 var_dump 来显示 i.

string(189) "{"0":"Choose Account Name","2":"Information and Communication Technology Equipment","3":"Office Equipment","4":"Furniture and Fixtures","5":"Communication Equipment","6":"Other Equipments"}"

尝试这样的事情,

    $.each(category_ids,function(account_id,name){
      var opt = $('<option />');           
      opt.val(account_id);
      opt.text(name);
      $(this).closest('td').next().find('select').append(opt);
    });
    $(this).closest('td').next().find('select option:first').attr('selected', 'selected');

应该是这样的。您需要使用更好的 selector 来获取您的 < select > 标签。

$.each(category_ids,function(account_id,name){
    var x = document.createElement('option');
    x.setAttribute('value', account_id);
    var y = document.createTextNode(name);
    $(x).append(y);

    $('#selectId').append(x)
});

编辑 经过进一步讨论,这看起来是一个更好的答案:

$(\".category_id\").change(function(){
    var _this = this;
    $(\"#account_id > option\").remove();
    $(\"#item_name_id > option\").remove();

    var  category_id={'category_id':$(this).val()};

 $.ajax({
       type: \"POST\",
       url: 'getCategory1/', 
       dataType: \"json\",
       data: category_id,
       success: function(category_ids){ 

 // category_ids = {"0":"Choose Account Name","2":"OfficeEquipment","3":"IT Equipment"}
               $.each(category_ids,function(account_id,name){

                  var opt = $('<option />');           
                  opt.val(account_id);
                  opt.text(name);

                  $(_this).closest('td').next().find('select').append(opt);

             });
          }

      });
});

这让很多人感到困惑。这是一个关于 "this" 范围的快速阅读,应该可以更清楚地理解这一点。http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

您似乎想要建立级联下拉菜单。用户必须先 select 类别,然后是帐户名称,依此类推...我说得对吗?

如果这就是你想要的。您的代码不正确,除非那些层叠的下拉菜单每个都只有一个选项。

$.ajax({
   type: \"POST\",
   url: 'getCategory1/', 
   dataType: \"json\",
   data: category_id,
   success: function(category_ids){ 
       // assume that your category_ids will be a string array.
       // ex: ["#cate01", "#cate02", "#cate03", "#cate04", "#cate05"]  

       $.each(category_ids, function(account_id,name) {
           // first loop,
           //   be account_id = 0, name = "#cate01"

           var opt = $('<option />');           
           opt.val(account_id);
           opt.text(name);

           // <option value="0">#cate01</option> is created.

           // this will be "#cate01", it is the same with the name value.
           // actually, you don't need to use this keyword here.
           $(this).closest('td').next().find('select').append(opt);

           // it will look up #cate01 and find its parent, its td and
           // moves to td right next to it, and finally settles on the select element inside it.
       });
   }

});

使用此代码,选项将不会堆叠在 select 元素上 因为目标选择框在整个每个循环中不断变化。 我怀疑还有更多在 category_ids 上。但是即使 `category_ids 不仅仅包含一个字符串数组,也不是这样做的方法。我不确定是否继续我的回答,因为您似乎足够聪明,已经知道如何调整这种代码。

总之..

$.ajax({
       type: \"POST\",
       url: 'getCategory1/', 
       dataType: \"json\",
       data: category_id,
       success: function(category_ids){ 

           $.each(category_ids, function(account_id,name) {

               // you need a list of option data here, 
               // fetching it though AJAX or something ( it's your call )

               // Let's say you get a set of option data like this at this point.
               /* 
                    optData : { 
                       cate01 : ["option01", "option02", "option03" ··· , "option10" ]
                    }
               */

               // I'm declaring this variable for improving readability.
               var targetDropdown = $(name).closest('td').next().find('select');
               $.each(optData.cate01, function(val, optionName) {
                   var opt = $('<option />');           
                   opt.val(val);
                   opt.text(optionName).appendTo(targetDropdown);
               }

           });
       }

    });

仅供参考

我不知道您要在每个 select 框中放入什么样的数据以及您实际拥有什么样的数据,但关键是您当前的代码是无法将选项堆积在一个 select 框上。

我只是建议了实现目标的方法。如果您向我提供确切的数据集,我指的是选项,我可以更准确地帮助您。顺便说一句,我想这对你来说已经足够了。