2

I have developed a search feature in my application. Users can search for streets by typing the address in an input box. Onkeyup, the a function is called that compares the input against a database full of addresses. The function gives back 5 suggestions which are showed below the inputbox like a sort of dropdownmenu. This works perfectly fine. The user can afterwards select one of the suggestions, which triggers another function.

What I want to implement now is that, when the user presses ENTER, the second function is automatically called with the first suggestion. I thought it would not be that difficult to program, but I'm facing some difficulties. When I press enter, the page refreshes instead of going to the function.

Here is my code:

<div id = "toolbar">
<form id ="suggestions">
    <input type = "text" id = "insertText" autocomplete="off" onkeyup = "if(event.keyCode == 13) {SearchAddress(option1.text)} else {giveSuggestion()}" onfocus='showOptions()'
    <option class="option" id = "option1" onmousedown = "searchAddress(option1.text)"></option>
    <option class="option" id = "option2" ... </option>
</form>
</div>

CSS

#toolbar {
        position: fixed;
        width: 100%;
        height: 25px;
        top: 0;
        left: 0;
        padding: 5px 10px;
        background: #ccc;
        border-bottom: 1px solid #333;
    }
#suggestions {
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        position: absolute;
        left: 310px;
        top: 5px;
        background-color: white;
        font-size: 12px;
    }
.option{
        display:none;
        cursor: default;
        padding: 0px 3px;
    }

Any suggestions?

Wout
  • 103
  • 1
  • 3
  • 6

3 Answers3

2

When you hit enter the browser tries to submit the form.

So, there are two possible solutions:

  1. Remove form tag, if you don't need to send any data from it to the backend.
  2. Add onsubmit="return false;" to the form tag.
Microfed
  • 2,832
  • 22
  • 25
0

I guess the browser didn't know what event is So......

<input type = "text" 
       id = "insertText"
       autocomplete="off" 
       onkeyup = "function(event){if(event.keyCode == 13) 
                                    {SearchAddress(option1.text)} 
                                  else {giveSuggestion()}"
       onfocus='showOptions()'}" />
Shnugo
  • 66,100
  • 9
  • 53
  • 114
AVAVT
  • 7,058
  • 2
  • 21
  • 44
0

The default behavior of form will refresh the page, so place replace the form tag to div, and handle the form submit yourself use library like jQuery or vanilla XMLHttpRequest object.

David Guan
  • 4,180
  • 1
  • 25
  • 32