javascript - jquery get data attributes from dynamically generated options -


i creating drop down dynamically after ajax , populating fields. calling jquery.data() set attribute want in future.

html

<input id="test" type="text" list="mylist"/> <datalist id="mylist"></datalist> 

js

$(function() { // assume data coming ajax call var data = [{     "name": "john",     "id": 1 }, {     "name": "jane",     "id": 2 }, {     "name": "judie",     "id": 3 }];  var generatedropdown = function(data) {     var datalist = $('#mylist');      (var = 0; < data.length; i++) {         var value = data[i].name + ' => ' + data[i].id;         $('<option>', {                 'class': 'myclass'             })             .val(value)             .data('extra', {                 'newid': data[i] * 100             })             .appendto(datalist);     } };  generatedropdown(data);   $('.myclass').on('select', function(selected) {     console.log($(selected).data('extra'));     console.log($(this).data('extra'));  }); }); 

here jsfiddle

my requirement access selected value drop down along data attribute have added. how can ?

i tried 2 console.log options mentioned above dont print anything.

in comparison htmlselectelement object, htmldatalistelement object doesn't have selectedindex property, seems have filter options getting possible selected option.

$('#test').on('change', function (/* event */) {     var val = this.value;     var data = $(this.list.options).filter(function() {          return this.value === val;     }).data('extra'); }); 

here demo. note data[i] * 100 results in nan (not number) value multiplying object number , doesn't make sense!


Comments

Popular posts from this blog

python - Mongodb How to add addtional information when aggregating? -

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

java - Incorrect order of records in M-M relationship in hibernate -