saminathan saminathan - 4 months ago 12
Javascript Question

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

Below is the code where I have created two dropdowns dynamically. If i select the second dropdown I would like to get the first dropdowns selected value.

Below is 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>


Below is the jQuery I tried:

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
}

Answer

The problem is with the closest method. It should be:

.closest('.selct_drp_dwn')

and then you should find the select:

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

With that in mind, you can still short your code to:

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

Another issue: Ids must be unique, you have duplicates of name1.

Comments