deruitda
deruitda

Reputation: 580

Cannot Get Value From Text box in IE When Triggering Function Via Key Event

I have a search box on my site that can be used by either clicking the search button, or hitting the enter key while the search box is focused. The issue I am experiencing only occurs in Internet Explorer (which I unfortunately have to support).

When clicking the button to perform the search, everything works as planned. When hitting enter however, I get some odd behavior. When debugging the javascript, I can see that the search query is empty. Here is all the javascript I am using, clicking the button and hitting enter both use the same search function.

$(document).ready(function () {
    var input = document.getElementById("txtSearch");
    if (input) {
        input.addEventListener("keyup", function (event) {
            //if the user hits enter
            if (event.keyCode == 70) {
                event.preventDefault();
                search();
            }
        });
    }
})


function search() {
    var searchstring = $('#txtSearch').dxTextBox('instance').option('value');
    //only search if there is a value in the text box
    if (searchstring != "") {         
        var url = window.location.origin + "/Search" + "?searchquery=" + encodeURIComponent(searchstring);
        window.location.href = url;
    }
}

The first line in the search function is the issue. After hitting enter the function is triggered, and the search string is set to an empty string rather than what is in the text box.

Upvotes: 1

Views: 338

Answers (1)

Jordan Papaleo
Jordan Papaleo

Reputation: 1511

You already have the event in your eventListener. I would recommend you just pass event.target.value to your search function. That makes it more functional. Having a function that gets its own info is a bad pattern.

To summarize:

  1. Get the value from your event: event.target.value
  2. Pass that to search as an argument
  3. Use the argument in your function instead of getting the search string

Upvotes: 1

Related Questions