0

I am filling a data-list in html using data from a Json . The options are being appended to the data-list with the value and label text . on click of an option , I want the value and the text to be inserted into a form text field .

The value of the option can be accessed and is successfully inserted into the text field. But I am not able to access the label of the option to insert it.

I have tried using $(this).innerhtml(); , $(this).text(); , $(this).label(); , $(this).innerhtml(); and so on..

all of which turned out to return null value (undefined) instead of the required string.

$(document).ready(function ()
{
    $.ajax({
        type: 'POST',
        url: '@Url.Action("MyJsonFunction")',
        datatype: 'json',
            success: function (data) {                    
                $.each(data, function (index, data) { $("#myid1").append("<option value='"+data.Value+"'label='"+data.Text+"'></option > ");})},
        error: function () 
        {
            alert("Something went wrong!");}});

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

         var s = $(this).val();
         var d = $(this).html();

         alert(d);

         $("#input1").val(s);
          $("#input2").val(d);
     });

});

The value of the option is being inserted to the input text field but the label of the option is null when i try to access it .

when i alert it , it displays either an empty string or "undefined" .

  • `label` in your code is an attribute you can use `$("option:selected" , $(this)).attr('label')` ..Also take a look at [HTML “data-attribute” vs simple “custom attribute”](https://stackoverflow.com/questions/33151713/html-data-attribute-vs-simple-custom-attribute) – Mohamed-Yousef Aug 19 '19 at 05:03

2 Answers2

0

Try this solution.you have to make any one option as selected, because on form load,none of your options are selected and it will surely alert as undefined.

$(document).ready(function ()
{
$("#colors").trigger('change');
});
$("#colors").change(function ()       {
  var d = $('#colors').find("option:selected").val();
  alert(d);
  $('#selvalue').val(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<label for="color">Favorite Color</label>
<input list="colors" name="color"> 

<datalist id="colors"> 
<option selected=selected value="Green"> 
<option value="Red"> 
<option value="Blue">
<option value="Yellow"> 
<option value="Orange"> 
</datalist>




<input type='text' id='selvalue' placeholder='Display seleted value'/>
Nijin P J
  • 1,302
  • 1
  • 9
  • 15
0
$('body').on('change','#myid1',function(){ alert( $(this).find(':selected').attr('label') ) });

Please try this code. I am sure this will work

Chirag Arora
  • 357
  • 3
  • 13