0

I am using a jQuery Plugin select2.js. how can i select data attribute of selected option using jQuery.

here is the code

<select class="select2">
  <option data-id="1" value="2"> CASE 1 </option>
  <option data-id="2" value="2"> CASE 1 </option>
  <option data-id="3" value="2"> CASE 1 </option>
</select>

$(document).ready(function(){

   $('.select2').select2();

   $('.select2').click(function(){
       //alert($(this).val());

   });
});

How i can get data-id of selected option using jQuery.

4 Answers 4

2

This has the same logic as select element. You can use default selectors.

$('.select2').change(function(){
    alert($(this).find('option:selected').data('id'))
});

But i recommend you to use change event instead of click on select boxes.

Sign up to request clarification or add additional context in comments.

Comments

0

this will give you the data attribute

$(this).data("id") 

Comments

0

You can find selected option using :selected selector and then use .data() to get/set data attribute value. you should also use change event instead of click event for select element:

$('.select2').change(function(){
  var selecteddataid = $(this).find('option:selected').data('id');
});

Comments

0

You can do it on change event, Here is fiddle

$(function() { 
    $(".select2").change(function(){ 
        var element = $(this).find('option:selected'); 
        var id= element.attr("data-id"); 
        alert(id);
    }); 
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.