fetching data-id in select tag using jquery

时间:2017-08-04 12:09:45

标签: jquery html

I'm currently studying how to get the values inside html values using data-id but the result is undefined.

jquery inside function add_equipment()

var new_id = $( 'option:selected', this ).data( 'id' );
console.log( new_id );

i also tried:

var new_id = $(this).find(':selected').data('id'); 
console.log( new_id );

and

var new_id = $(this).find(':selected').attr('data-id');
console.log( new_id );

my select tag

<select class="form-control product-name" id="product-name">
  <option value="default" selected disabled>Select Equipment Type</option>
  <option value="2.00" data-id="1">pencil </option>
  <option value="5.00" data-id="2">pen </option>
  <option value="7.00" data-id="3">marker </option>
</select>

THANK YOU IN ADVANCE.

2 个答案:

答案 0 :(得分:3)

Problem with you implementation is that this refers to window object not <select> element, thus it didn't worked.

As you have provided ID attribute to <select> element, use it

var new_id = $('#product-name').find(':selected').data('id');

答案 1 :(得分:1)

you need use data() method to get data-id attribute id.

$(function(){
  $('#product-name').on('change',function(){
    console.log($('#product-name option:selected').data('id'));
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control product-name" id="product-name">
  <option value="default" selected disabled>Select Equipment Type</option>
  <option value="2.00" data-id="1">pencil </option>
  <option value="5.00" data-id="2">pen </option>
  <option value="7.00" data-id="3">marker </option>
</select>

try this one.