Maranatha Maranatha - 11 months ago 37
jQuery Question

Getting the index of a dropdown array on change event

I have multiple dropdowns and they are named like this:

pricing[1], pricing[2], pricing[3]
and so on.
event of every dropdown named
, I would like to get the index of the
, which is 'x' in that case, as well as the selected value.


foreach($allindichapter as $chapter){
echo "<select name='pricing[".$chapter['CHAPTER']."]' id='pricing[".$chapter['CHAPTER']."]' class='pricing' style='width:100%'>";

foreach($indimonthly as $imchapter => $type){
foreach($type as $typ => $price){
if($imchapter == $chapter['CHAPTER'])
echo '<option value="'.$chapter.'">Monthly - '.$price.'Php</option>';
echo "</select>";

The problem is, I cannot even enter the
function for the dropdown. I have tried different ways such as:



var id = $(this).attr('id');

I have also used the
with a JQuery function.
Any help will be appreciated.

For reference, this is what I am trying to achieve:

enter image description here

When the Pricing is changed, I will update the Duration dropdown.

Answer Source

So if I understood correctly, you want the index of the select and not the one of the selected option.

In that case you have to look at $(this).attr('name') and extract the index from that string.

Alternatively you could add a data attribute to the selects with only the index, which is easier to retrieve than extracting it from the name.

I made an example on how to do both.

Also be sure if the selects are included via Ajax, you can't use .bind or .change but .on instead.

    'Select name index: ' + $(this).attr('name').replace(/pricing\[(\d+)\]/, '$1') + 
    '\nSelect data index: ' + $(this).data('index') + 
    '\nValue: ' + $(this).val()
<script src=""></script>
<select name="pricing[1]" data-index="1">
  <option value=""></option>
  <option value="1-1">1-1</option>
  <option value="1-2">1-2</option>
<select name="pricing[2]" data-index="2">
  <option value=""></option>
  <option value="2-1">2-1</option>
  <option value="2-2">2-2</option>
<select name="pricing[3]" data-index="3">
  <option value=""></option>
  <option value="3-1">3-1</option>
  <option value="3-2">3-2</option>