Javascript detect a selection of browser AutoComplete value

无人久伴 提交于 2020-01-12 15:05:53

问题


I have a text field with an onkeyup event. But this event is not fired when I select a browser autoComplete value. I have added an onclick event, but it doesn't work.

I have tested many solutions posted on stackoverflow for catching the browse autocoComplete selection, but nothing has resolved this problem.

Try this simple example to see the issue (reproduced on Firefox 3.6, Chrome 10.0 and IE8):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
    <script type="text/javascript">
    //<![CDATA[
        function onkeyupInput(){
            $('#divResult').text($('#myInput').val());
        }
    //]]>
    </script>
</head>
<body>
    <form name="myForm" action="#">
        Tape a value and send it. Then select this value with your browser AutoComplete value :<br />
        <input id="myInput" name="myInput" type="text" onkeyup="onkeyupInput();" onclick="onkeyupInput();" value="" />
        <input type="submit" />
    </form>
    Result of onkeypress and onclick :
    <div id="divResult"></div>
    <br />
    <b>The issue : Result of onkeypress and onclick is not update when an autocomplete value of a browser is selected.</b>
</body>
</html>

Thanks!


回答1:


Newer browsers support the oninput event:

$(function () {
  $('#myInput').on("input",function() {
    $('#divResult').text($(this).val());
  });
});

<input id="myInput" name="myInput" type="text" value="" />

If you need to support older browsers, try

var tId = "";
function monitor() {
 $('#divResult').text($('#myInput').val());
}

$(function () {
  $('#myInput')
  .focus(function() {
      tId=setInterval(monitor,100);
  })
  .blur(function() {
      clearInterval(tId);
  });
});


来源:https://stackoverflow.com/questions/5430342/javascript-detect-a-selection-of-browser-autocomplete-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!