Getting the value of other attributes to select a data source

I have a datalist:

<datalist id="subjects"> <?php foreach($subjects as $v){ ?> <option data-subjectid="<?php echo $v[2]; ?>" value="<?php echo ucwords($v[1]); ?>"><?php echo ucwords($v[1]); ?></option> <?php } ?> </datalist> 

What I want to do is get the value stored in the data-subjectid attribute of the selected value. What I have done so far is to call the .each() function in jQuery as follows:

 //on Select Change var selectedvalue = $(this).val(); $('#subjects option').each(function(){ if(current_value == selectedvalue){ //get the data-subjectid of current value } }); 

Is there a better and faster way to do this?

+4
source share
1 answer

I'm not sure if this is faster (I'm not 100% sure how this selector works under covers), but you can use : selected selector to make the code a little cleaner.

 var subjectId = $('#subjects option:selected').attr('data-subjectid'); 
+1
source

Source: https://habr.com/ru/post/1400945/


All Articles