Maranatha Maranatha - 1 month ago 5
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.
onchange
event of every dropdown named
pricing[]
, I would like to get the index of the
pricing[x]
, which is 'x' in that case, as well as the selected value.

HTML:

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>';
break;
}
}
echo "</select>";
}


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

$('select').change(function(){
console.log($('option:selected',this).index());
});

$(function(){
$('select').change(function(){
console.log($('option:selected',this).index());
});

$('.pricing').bind("change",function(){
var id = $(this).attr('id');
alert(id);
});`


I have also used the
onchange="pricechange()"
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

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').change(function(){
  alert(
    'Select name index: ' + $(this).attr('name').replace(/pricing\[(\d+)\]/, '$1') + 
    '\nSelect data index: ' + $(this).data('index') + 
    '\nValue: ' + $(this).val()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>
<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>
<select name="pricing[3]" data-index="3">
  <option value=""></option>
  <option value="3-1">3-1</option>
  <option value="3-2">3-2</option>
</select>