根据动态列表中的另一个下拉选项更改下拉选项

时间:2017-01-23 10:06:29

标签: jquery

我试图从下拉城市更改“建立”的下拉值。行是动态添加的。如何使用selectC1更改selectE1

<script>
    var olList = $('#olcityList');

    var $li = $('li.list').clone();


    // Addding a new list element to the list
    $('#plus').click(function(){ 
        var index = olList.find('li').length+1;

        //Create clone to manipulate its elements
        var li = $li.clone();
        li.attr('id',  index);
        li.find('.city select').attr('id', 'selectC' + index);
        li.find('.esta select').attr('id', 'selectE' + index);

        olList.append(li);
    });

    // Get the selectC id when changed 
    $('select').change(function(){

    console.log("parent id: " + $(this).closest('li').attr('id'));
    console.log("Current id: " + $(this).attr('id'));

    // To manipulate SelectE id 
    var tempParentId= $(this).closest('li').attr('id');
    console.log( $('#estaList'+tempParentId).val()   );

});
</script>

<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol id="olcityList">
        <li class="list" id="1">
            <div class="city">
                <select id="selectC1">
                    <option value=1>Delhi</option>
                    <option value=2>Mumbai</option>
                </select>
            </div>

            <div class="esta">
                <select id="selectE1">
                    <option value="1">Delhi 1</option>
                    <option value="1">Delhi 2</option>
                    <option value="2">Mumbai 2 </option>
                    <option value="2">Mumbai 1</option>
                </select>
            </div>
        </li>
</ol>

使用jsp填充下拉文本和值。 但是,选择一次之后就无法正常工作。

使用此作为参考
Use jQuery to change a second select list based on the first select list option

1 个答案:

答案 0 :(得分:0)

因为您正在动态操作DOM加上按钮,所以每次按下加号按钮都需要调用.change() - 处理程序。

试试这段代码:

$(document).ready(function(){
    myChange();
})

var olList = $('#olcityList');

var $li = $('li.list').clone();

// Addding a new list element to the list
$('#plus').click(function() {
  var index = olList.find('li').length + 1;

  //Create clone to manipulate its elements
  var li = $li.clone();
  li.attr('id', index);
  li.find('.city select').attr('id', 'selectC' + index);
  li.find('.esta select').attr('id', 'selectE' + index);

  olList.append(li);
  myChange()
});

function myChange() {
  // Get the selectC id when changed 
  $('select').change(function() {

    console.log("parent id: " + $(this).closest('li').attr('id'));
    console.log("Current id: " + $(this).attr('id'));

    // To manipulate SelectE id 
    var tempParentId = $(this).closest('li').attr('id');
    console.log($('#estaList' + tempParentId).val());

  });
}