google maps autocomplete bounces back already cleared text …odd…odd…odd

强颜欢笑 提交于 2019-12-24 03:55:16

问题


I have this odd behavior from Google MAPs autocomplete (or maybe I miss sth)... ideas? The odd:

  1. You enter sth into the input, e.g. 'London'
  2. You press [ENTER]
  3. You press [CLEAR] button
  4. You click into the 'input'
  5. You click outside the 'input'

....... and voila! The already cleared in step-3 text ('London' in our example) is right-back into the input...Why?

And here is the code:

<!DOCTYPE html>
<html>
<head>
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
</head>
<body>

    <h1>MY FORM</h1>
    <input type='text' id='myInput' size='50' placeholder='Enter text'>
    <input type='button' value='clear' onclick='clearInput()'>

    <script>
                var myInput = document.getElementById('myInput');
                var autocomplete = new google.maps.places.Autocomplete(myInput);
                function clearInput(){
                    myInput.value = '';
                }

                myInput.addEventListener('change', function(){
                        console.log(event['target']['value']);

                }, false);

    </script>
    </body>
</html>

回答1:


Answering the "why" complicated, because the source of the API-source is compressed, hard to say what's really going on there.

Of course the value of the input must be stored somewhere, because it must be restored in some cases(e.g. when you switch between the values of the dropdown).

Basically an autocomplete is listening for 4 events in the input:

focus, keydown, keyup, blur

None of these events will fire in your function, so the autocomplete may not recognize the new value.

Possible solution:trigger these events in your function:

function clearInput(){
  google.maps.event.trigger(myInput,'focus');
  myInput.value = '';
  google.maps.event.trigger(myInput,'keydown',{keyCode:46});
  google.maps.event.trigger(myInput,'keyup',{keyCode:46});
  google.maps.event.trigger(myInput,'blur');
}

You may send a bug-report, this is not the expected behaviour and should be fixed.



来源:https://stackoverflow.com/questions/21617795/google-maps-autocomplete-bounces-back-already-cleared-text-odd-odd-odd

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