yaylitzis
yaylitzis

Reputation: 5534

Read a value from datalist in Javascript

In a form input I have a datalist, which I load it with JSON.

<div class="form-group">
  <div class="col-md-5">
       <input type="text" id="product" list="products" class="form-control" name="product" />
       <datalist id="products"></datalist>
    </div>                      
</div>

The JS for the datalist is this:

var dataList = document.getElementById('products');
var input = document.getElementById('product');
var request = new XMLHttpRequest();

request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {
      // Parse the JSON
      var jsonOptions = JSON.parse(request.responseText);

      // Loop over the JSON array.
      jsonOptions.forEach(function(item) {
        var option = document.createElement('option');

        option.value =item.product;
        option.text = item.description;
        dataList.appendChild(option);
      });

      // Update the placeholder text.
      input.placeholder = "product";
    } else {
      // An error occured :(
      input.placeholder = "errorr :(";
    }
  }
}; 

// Update the placeholder text.
input.placeholder = "Loading options...";

// Set up and make the request.
request.open('GET', 'products.json', true);
request.send();

Now I try to do the following. When the user selects sth from the list, I want to get the value. I tried 2 ways to get the value without success.. (I inserted the following after the above code):

$(function() {
    $('#product').on('change keyup', function() {

        var i = this.selectedIndex;
        var opt = $('option[value="'+$(this).val()+'"]');
        console.log("1 --> " + opt + " 2 -->" + i);

    });
});

What I get when i try to select sth from the datalist is:

1 --> [object Object] 2 -->undefined

$(function() {
  $('#product').on('change keyup', function() {
console.log($(this));
    var i = $(this).selectedIndex;
    var opt = $('option[value="' + $(this).val() + '"]');
    console.log("1 --> " + opt + " 2 -->" + i);
   

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="col-md-5">
    <input type="text" id="product" list="products" class="form-control" name="product" />
    <datalist id="products">
      <option value="Internet Explorer">1</option>
      <option value="Firefox">2</option>
    </datalist>
  </div>
</div>

Upvotes: 1

Views: 1514

Answers (3)

ashkufaraz
ashkufaraz

Reputation: 5297

Try this

$("#products option[value='"+$("#product").val()+"']").text()

Upvotes: 0

Parminder Singh
Parminder Singh

Reputation: 351

There is no selectedIndex for datalist because its hidden from the browser. If you want to get the value of text field then you can use this:

   $(function() {
     $('#product').on('blur', function() {
       var i = this.value;
       var opt = $('option[value="' + $(this).val() + '"]');
       console.log("1 --> " + opt + " 2 -->" + i);

     });
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="col-md-5">
    <input type="text" id="product" list="products" class="form-control" name="product" />
    <datalist id="products">
      <option value="Product1">
        <option value="Product2">
          <option value="Product3">
            <option value="Product4">
              <option value="Product5">
    </datalist>
  </div>
</div>

Upvotes: 1

Neckster
Neckster

Reputation: 96

You should use input event instead of change. It will give you an ability to trigger, when user select some value from datalist.

$('#product').on('input keyup', function() {
  var options = $('#products option');
  var inputValue = $('#product')[0].value;

  for (var i = 0; i < options.length; ++i)
    if (options[i].value === inputValue)
      console.log(
          'Selected value from option is ==>',
          options[i].value
      );

});

Upvotes: 0

Related Questions