How to set the value of select option

时间:2015-04-29 00:34:41

标签: jquery dynamic drop-down-menu

I am trying to populate the dropdown menu based on the selection of the first menu. using the code below it will just make the next dropdown to be empty

  $(\".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);

             });
          }

      });
});

The controller function I used:

  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));
    }

The model function

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; }
    }

The data to be loop in the $.each will be coming form the controller in json format. I used var_dump to display 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"}"

Dropdown Form

3 个答案:

答案 0 :(得分:1)

尝试这样的事情,

    $.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');

答案 1 :(得分:1)

应该是这样的。你需要使用一个更好的选择器来获得你的&lt;选择&gt;标签

$.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);

             });
          }

      });
});

这会使很多人绊倒。这是一个很好的快速阅读&#34;这个&#34;应该让这个更清楚易懂的范围。http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

答案 2 :(得分:1)

看起来您想要构建级联下拉菜单。用户必须首先选择类别,然后选择帐户名称,依此类推......我是对的吗?

如果这就是你想要的。您的代码不正确,除非这些级联的dropdownmenus每个只有一个选项。

$.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.
       });
   }

});

使用此代码,选项不会叠加在选择元素上,因为目标选择框会在整个循环中不断变化。我怀疑{{1}还有更多内容}。但即使`category_ids不仅仅是一个字符串数组,它也不是这样做的。我不确定继续我的回答,因为你似乎已经足够聪明地知道如何调整这种代码了。

反正..

category_ids

<强> FYI

我不知道您试图在每个选择框中添加哪种数据以及您实际拥有哪种数据但重点是您当前的代码无法堆积单个选择框上的选项。

我刚刚提出了实现目标的方法。如果您向我提供确切的数据集,我的意思是选项,我可以更准确地帮助您。我想这对你来说已经足够了。