4

I've got some JQuery which works fine. It loads all the autocomplete values, and upon clicking them, they load the searchdata.php which performs all the searching. This works.

What I can't figure out is, if the user decides they don't want to select an autocomplete value and hit enter instead, how do I get it to perform the searchdata.php on the value that is in the search input upon hitting enter WITHOUT reloading the page? I've tried bind and live and can't get it to work.

<script type="text/javascript">
$(document).ready(function() {

var availableTags = <?php echo json_encode($findrow);?>;

  $("#search_input").watermark("Begin Typing to Search");
  $('#searchresultdata').append(sendSelected);

    $("#search_input").autocomplete({
        source: availableTags,
        select: function(event, ui) {
          sendSelected(ui.item.value);
          }
        });

function sendSelected(_val){
    var search_input = _val;
    if (search_input =='') search_input ='*';
    var dataString = 'keyword='+search_input;

    if (search_input.length > 2 || search_input=='*') {
       $.ajax({
            type: "GET",
            url: "core/functions/searchdata.php",
            data: dataString,
            success: function(server_response) {
                $('#searchresultdata').empty();
                $('#searchresultdata').append(server_response);
                $('span#category_title').html(search_input);
            }
        });
    }
}
});
</script>
K20GH
  • 6,032
  • 20
  • 78
  • 118
  • possible duplicate of [jQuery AutoComplete Trigger Change Event](http://stackoverflow.com/questions/6431459/jquery-autocomplete-trigger-change-event) - same but use select event instead (they should have the same handler) – Potatoswatter May 15 '12 at 03:00

3 Answers3

7
$("#search_input").keypress(function(e) {
  if(e.keyCode == 13)
     {
         e.preventDefault();
         sendSelected(this.value);
         $(this).autocomplete('close');
     }
});
Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • Ah thanks, I was just trying that but had it included in the autocomplete statement. Is there a way to close the autocomplete box when they hit enter so it doesn't cover my results? – K20GH May 11 '12 at 14:02
  • 1
    @K20GH there sure is; see my edit. Add `$(this).autocomplete('close')` to fire the close method. – Evan Davis May 11 '12 at 14:04
3
$("#search_input").on('keyup', function(event) {
  if(event.which == 13)  // event.which detect the code for keypress in jQuery
     {
         event.preventDefault();
         sendSelected(this.value);
     }
});
The System Restart
  • 2,873
  • 19
  • 28
2

you can use event.preventDefault() on the action and it wont submit the page, you just have to be sure to juggle it on and off when you need to

http://api.jquery.com/event.preventDefault/

raddrick
  • 4,274
  • 2
  • 27
  • 33