2

I have implemented ajax live search on my website.It does work for all browsers but when it comes to touchscreen it doesn't show any results.I think the touch event is not being detected by the code but even upon my several searching on net I have no clue what to do.Here is my code and any help would be appreciated

        $(document).ready(function () {

        $("#search").keyup(function (e){

            var inp = String.fromCharCode(e.keyCode);

            if (/[a-zA-Z0-9-_ ]/.test(inp)) {

                $.ajax({

                    url: '/search.php',

                    type: 'POST',

                    data: "keyword=" + $(this).val(),

                    success: function (data) {

                        data = $.parseJSON(data);

                        if (data['response'] == true) {

                            $("#search_results").html(data['html']).show();

                        } else {

                            alert("Please try again.");

                        }

                    }

                });

            }

        });



        function hide_search_results(e) {

            var container = $("#search_results");

            if (!container.is(e.target) && container.has(e.target).length === 0) {

                window.displayBoxIndex = -1;

                container.hide();

            }

        }



        $(document).mouseup(function (e) {

            hide_search_results(e);

        });

    });
zish
  • 607
  • 2
  • 6
  • 15

1 Answers1

2

I believe that you also need touchend event to make you script supporting touch screens.

Try to use two events with .on() instead of .keyup().

$('#search').on('touchend keyup', function(e) {
  ...
});

As an alternative you can use input event instead of touchend.

voloshin
  • 536
  • 7
  • 17
  • Thanks a lot it has started working but the problem is now with this line var inp = String.fromCharCode(e.keyCode) .It is not fetching the exact input from touchscreen. Can you help me regarding this issue. – zish Sep 12 '17 at 09:12
  • Right, there can be a problem too because `e.keyCode` is a property of `keydown / keyup` events and won't work with other events. Is it necessary to get inputted text in this way? Perhaps, `$(this).val()` might be good as well? Or there're some other needs to use `String.fromCharCode(e.keyCode)`? – voloshin Sep 12 '17 at 09:19
  • 1
    Thanks a lot for your time. There was no specific reason for using String.fromCharCode(e.keyCode) So I have changed it to $(this).val() now and everything is working fine. – zish Sep 12 '17 at 10:06