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 to get the value stored in the data-subjectid
attribute of the value that is selected. What I have been doing up until now is to call the .each()
function in jQuery like this:
//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?
I'm not sure if this is faster (I'm not 100% sure how this selector works under the covers) but you can use the :selected selector to make the code a little cleaner.
var subjectId = $('#subjects option:selected').attr('data-subjectid');