Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete enter key issue

I have a text box for searching using jQuery autocomplete. When I type something in text box, it is showing the suggestions out of which none is selected.

I found out that selectFirst: true is not supported now. If I select an item in the drop down list and press enter, it is working fine.

The problem is that if user enters app for apple and presses the enter key, it tries to submit the form with app. The form should only be submitted with one of the values from the drop down list.

I tried to disable the form submit on pressing enter so that I could submit form from JavaScript but couldn't find a solution.

Here is my code:

$("#searchtext").autocomplete({
    source: path + 'autocompletesearch?category=' + $("select[name='category'] option:selected").val(), 
    width: '500px', 
    matchContains: true, 
    select: function(event, ui){
        $(".searchform").attr("action", path + "fullproductinfo/" + ui.item.id);
        $("input[name='searchid']").val(ui.item.value);
        $(".searchform").submit();
    }
});

And my form:

        <form method="post" action="search" class="searchform">
            <div class="searchdiv">
                <input type="text" id="searchtext" name="searchtext"
                    placeholder="Search a product or a brand" autocomplete="off"/>
            </div>
            <div class="searchbutton">
                <input type="button" name="btnsearchproduct" value="Search" />
            </div>
            <div class="clear"></div>
        </form>

Note that there is <input type='button' and not 'submit', so default enter pressing should not work for form. It is the autocomplete i guess that is submitting the form on submit.

like image 552
Ashutosh Avatar asked Jul 10 '14 03:07

Ashutosh


2 Answers

If you are using this: http://jqueryui.com/autocomplete/

Then you want first item to autoFocus, you can use that option now:

$( ".selector" ).autocomplete({ autoFocus: true });

Mentioned in documentation: http://api.jqueryui.com/autocomplete/

EDIT

Since you have enter key issue, you can try like this:

$(".selector").keydown(function(event){
    if(event.keyCode == 13) {
      if($(".selector").val().length==0) {
          event.preventDefault();
          return false;
      }
    }
 });
like image 184
j809 Avatar answered Nov 26 '22 03:11

j809


I had a similar issue & this is how I resolved it

if ($(".selector").val().length > 0) {
var options = $(".selector").autocomplete("option");
var fromAutocomplete = false;

jQuery.each(options.source, function(index, device) {
if ($(".selector").val() == options.source[index]) {
    fromAutocomplete = true;
}
});

if (!fromAutocomplete) {
$(".selector").val("");
    $(".selector").attr("disabled", false);
    return false;
}
}
like image 33
AK Imran Avatar answered Nov 26 '22 02:11

AK Imran