Javascript Form How to - Add Event handler for input and datalist








Question

We would like to know how to add Event handler for input and datalist.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--  w ww.  j  a v a2s.  c o  m-->
    document.querySelector('input').oninput = function() {
        console.log(this.value);
    };
}
</script>
</head>
<body>
  <input type="text" name="product" list="productName" />
  <datalist id="productName">
    <option value="Pen">Pen</option>
    <option value="Pencil">Pencil</option>
    <option value="Paper">Paper</option>
  </datalist>
</body>
</html>

The code above is rendered as follows: