【问题标题】:How to set the value of select option如何设置选择选项的值
【发布时间】:2015-07-08 01:35:47
【问题描述】:

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

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

【问题讨论】:

  • 您的选择器是否返回任何内容?你能包括你的html吗?甚至可能是一个jsfiddle。我认为您的选择器不正确。 $.each 中的 $(this) 不会是你想要的。
  • 是的,如果我在 $.each 中使用 $(this),它会导致未定义,但如果我在 $.each 之外使用它,它会给出未定义的结果。
  • ajax 调用在哪里...是否在事件处理程序中
  • 另一个下拉菜单的onchange事件触发
  • 您是否尝试构建级联下拉菜单并希望在下一个选择框上堆叠选项?

标签: jquery dynamic drop-down-menu


【解决方案1】:

应该是这样的。您将需要使用更好的选择器来获取您的 标签。

$.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/

【讨论】:

  • 是的,如果只涉及一组字段,它会以这种方式工作,但在我的情况下,有多行字段不适用,这就是我在 jquery 中使用 $(this) 的原因。
  • 我不认为 $(this) 是你认为的那样。如果你做一个 console.log($(this)); 你会得到什么到那时?
  • 看起来 $(this) 可能指的是每个循环函数。就像我之前所说的,您需要找到一种更好的方法来定位选择元素。如果不了解更多关于代码的信息,几乎不可能调试它。这个 ajax 调用是如何被触发的?页面 DOM 是什么样的?
  • 打开后立即输入“更改”功能(第 2 行)添加此行... var _this = this; ...现在您将引用 _this 中的原始调用对象。所以稍后在你的每个你应该能够... $(_this).closest('td').next().find('select').append(opt);
  • 您通过 ID 定位对象,这不能是动态的。您必须通过类名或 DOM 中的位置来定位它们。假设 #account_id 是下一个选择并且有一个 account_id 类,你可以这样做.. $(_this).closest('td').next().find('select.account_id &gt; option').remove(); ... 请注意你把它放在哪里,如果它在每个循环中,你将删除它们正在把它们放进去。
【解决方案2】:

试试这样的,

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

【讨论】:

  • 这不可能。在 $.each 中,this 不会引用 DOM 元素。
  • 我怎样才能解决它上面的代码在控制台中返回相同的结果 undefine。 '[prevObject: jQuery.fn.jQuery.init[0], context: undefined, selector: "select option[0]", jquery: "1.9.0", constructor: function...]'
【解决方案3】:

您似乎想要构建级联下拉菜单。用户必须先选择类别,然后再选择帐户名称,等等……我说的对吗?

如果那是你想要的。除非那些级联下拉菜单每个只有一个选项,否则您的代码是不正确的。

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

});

使用此代码,选项不会叠加在选择元素上因为目标选择框在整个每个循环期间都在不断变化。我怀疑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);
               }

           });
       }

    });

仅供参考

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2018-02-28
    • 2011-10-27
    • 2015-05-30
    • 2019-04-29
    • 1970-01-01
    • 2019-09-05
    • 2019-04-28
    相关资源
    最近更新 更多