简体   繁体   中英

how to get index in selected item on change event (select box)?

I have 4 dropdown in my page .I want to know which dropdown is selected or changed using index,.But every time i am getting 0 index.here is my code

https://jsbin.com/fapahosenu/1/edit?html,js,output

$(function(){
  function dropdownChangeHandler(){
    console.log($(this).index())
  }
  $('[data-dropdown="dropdowns_js"]').on('change',dropdownChangeHandler);
})

this is not I am wanted ..I want if I change first dropdown it gives me 0 . I change second dropdown it gives me 1 .I change third dropdown it gives me 2

The issue is because you're getting the index() from the select yet they are not siblings, hence they all return 0 .

To fix this pass a selector to index() which is the group of elements you wish to find the index in, like this:

 $('[data-dropdown="dropdowns_js"]').on('change', function() { var index = $(this).index('[data-dropdown="dropdowns_js"]'); console.log(index); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <span> <select class="dropdowns_js" data-dropdown="dropdowns_js" data-key="bank"> <option selected="true" disabled="true" value="0">Select Bank</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> </span> <span> <select class="dropdowns_js" data-dropdown="dropdowns_js" data-key="state"> <option selected="true" disabled="true" value="0">Select State</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> </span> <span> <select class="dropdowns_js" data-dropdown="dropdowns_js" data-key="district"> <option selected="true" disabled="true" value="0">Select District</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> </span> 

像这样添加事件onclick并通过function dropdownChangeHandler(1)传递值

Try with below function it will give you the selected drop-down index. Please mark as answer, if your problem resolve with my solution

function dropdownChangeHandler(){
  $('.dropdowns_js').each(function(a,b){       
    if($(this).is(":focus"))
    {
      console.log(a);
    }
  }); 
}

If you select state drop-down, It will give you 1 as selected index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM