I have a input type text with datalist that contains duplicate option values
<input type="text" id="my-input" list="data-list">
<datalist id="data-list">
<option value="John" data-id="1"></option>
<option value="George" data-id="2"></option>
<option value="John" data-id="3"></option>
</datalist>
What options i have to get the data-id
when i select option. For example if i select the the second John
to get 3
as id. I just found this:
$("#data-list option[value='" + $('#my-input').val() + "']").attr('data-id');
but if i chose the second john it returns 1
as id, whitch is incorrect.
You can add an index to duplicate option in datalist
. So you should loop through options and in loop select any option in datalist
has same value
and add index to value
attribute of it.
$("datalist option").each(function(){
var sameOpt = $(this).parent().find("[value='"+this.value+"']:gt(0)");
sameOpt.val(function(i, val){
return val+'-'+(sameOpt.index(this)+2);
});
});
$("datalist option").each(function(){
var sameOpt = $(this).parent().find("[value='"+this.value+"']:gt(0)");
sameOpt.val(function(i, val){
return val+'-'+(sameOpt.index(this)+2);
});
});
$("#my-input").change(function(){
var v = $("#data-list option[value='"+this.value+"']").attr('data-id');
console.log(v);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my-input" list="data-list">
<datalist id="data-list">
<option value="John" data-id="1"></option>
<option value="George" data-id="2"></option>
<option value="John" data-id="3"></option>
<option value="George" data-id="4"></option>
<option value="John" data-id="5"></option>
</datalist>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With