简体   繁体   中英

Fetching attribute on change event Jquery

I have specified attribute to tag that I want to fetch using jquery.

<select id='duration' name='duration'>
  <option value=''>Select Duration</option>
  <option value='10' data-cost='50'>10 Min</option>
</select>

Here is my jquery code.

$(document).ready(function(){
   $('#duration').change(function(){
       var cst=$(this).data('cost');   // not working
       var cst=$('#duration').data('cost');
       alert(cst);

   });
});

It is showing value undefined in alert. I'm I doing anything wrong ?

data is attribute of option tag not select tag this represent select tag

Try this JSFIDDLE

$(document).ready(function(){
   $('#duration').change(function(){
       var cst=$(":selected",this).data('cost');   // not working
       alert(cst);    
   });
});

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