如果我选择第二个下拉框,如何获取第一个下拉框值

how to get first dropdown box value if i select second dropdown box

本文关键字:获取 第一个 选择 第二个 如果 何获取      更新时间:2023-09-26

下面是我动态创建两个下拉列表的代码。如果我选择第二个下拉列表,我想获取第一个下拉列表的选定值。

以下是 HTML:

<div class="selct_drp_dwn" id="row1">
    <select class="drop_dwn_mult" id="name1" onchange="changeBox2(this);">
        <option>Sample1</option>
        <option>Sample2</option>
        <option>Sample3</option>
        <option>Sample4</option>
    </select>
    <select class="drop_dwn_mult1" id="name1" onchange="changeBox3(this);">
        <option>Please select</option>
        <option>sam</option>
    </select>
    <i class="fa fa-minus-square remove" aria-hidden="true"></i>
    <i class="fa fa-plus-square" aria-hidden="true" id="btnAdd"></i>
</div>

以下是我尝试过的jQuery:

function changeBox3(val1)
{
    var a = val1.id;
    alert(a);
    var c = '#'+a;      
    var b = $(c).closest('select .drop_dwn_mult option:selected').val();
    alert(b);//I am getting undefined
}

问题出在最接近的方法上。它应该是:

.closest('.selct_drp_dwn')

然后你应该找到选择:

.find('.drop_dwn_mult').not(val1).find('option:selected')

考虑到这一点,您仍然可以将代码缩短为:

function changeBox3 (val1)
{
  var a = $(val1); // <- you passed `this` to val1 which is already a reference
                   //    to the element, thus not need to find the id
  var b = a
           .closest('.selct_drp_dwn')
           .find('.drop_dwn_mult')
             .not(val1)
           .find('option:selected')
           .val();
  alert(b);
}

另一个问题:Id 必须是唯一的,您有重复的 name1 .