bharath
bharath

Reputation: 395

how to get the value of data-value attr of selected datalist item

here is my datalist items with data-value attribute. i want to get the value of data attribute on change.

 <div class="col-md-3 "> 
  <input type="text" class="form-control" list="items" id="proname" placeholder="Product Name" style="margin-left: 12px;"> 
  <datalist id="items">
    <option data-value="120.0">
      Chicken Biryani() 57
    </option>
    <option data-value="100.0">
      chiken manchuriya() 58
    </option>
  </datalist>
</div>

i want to get the attr value on change of #proname

i tried the below code

$(document).ready(function() {
  $("#proname").change(function(){
    var proName=$("#proname").val();

    alert($("#proname option").find(':selected').data('data-value'));//out-put : undefined
  });
});

how would i get the data-value attribute value . please help me out.

Upvotes: 1

Views: 3341

Answers (2)

Nirali
Nirali

Reputation: 1786

Change your code

From

$(document).ready(function() {
    $("#proname").change(function(){
        var proName=$("#proname").val();

        alert($("#proname option").find(':selected').data('data-value'));//out-put : undefined

    });
});

To

$("#proname").change(function(){

  var proName=$("#proname").val();
   var value = $('#items option').filter(function() {
     return this.value == proName;
   }).data('value');
  var msg = value ? value : 'No Match';

alert(msg);

});   

Upvotes: 1

Samir Mammadhasanov
Samir Mammadhasanov

Reputation: 875

You can use data('value') or attr('data-value')

Upvotes: 1

Related Questions