user5547019
user5547019

Reputation:

JQuery autocomplete only if certain condition is met

I'm using JQuery autocomplete for a textbox within my .aspx page. The page contains a dropdown from where the user can select several different categories and is combined with a textbox where they can input a search term. Now, the issue is that I only need the autocomplete to work for one of the category options. My code looks something like this: .aspx :

<asp:DropDownList ID="DropDownList1" runat="server"  AutoPostBack="true" style="margin-left: 55px; margin-right: 10px;" Height="31px" >
               <asp:ListItem  Text="Name" Value="Name"></asp:ListItem>
               <asp:ListItem Text="JobTitle" Value="JobTitle"> </asp:ListItem>
                <asp:ListItem Text="City" Value="City"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"  ></asp:TextBox>

Code behind for the dropdown/ textbox :

void ResultsFilter()
{
    if (DropDownList1.SelectedValue.ToString() == "Name")
    {

        ObjectDataSource1.FilterExpression = "Name LIKE '%" + TextBox1.Text + "%' ";

    }
    else if (DropDownList1.SelectedValue.ToString() == "JobTitle")
    {

        ObjectDataSource1.FilterExpression = "JobTitle LIKE '%" + TextBox1.Text + "%' ";

    }
    else if (DropDownList1.SelectedValue.ToString() == "City")
    {

        ObjectDataSource1.FilterExpression = "City LIKE '%" + TextBox1.Text + "%' ";

    }
 }

And the Javascript for the autocomplete:

<script type="text/javascript">
     $(function() {
        var availableTutorials = [

           "Director",
           "Broker",
           "Medical",
           "R&D",
           "Sales Executive",

        ];
         $("#TextBox1").autocomplete({
            minChars: 0,
            delay: 0,
            source: availableTutorials, minLength:0
        }).on('focus', function() { $(this).keydown();

        });

     });
  </script>

So basically I only want the autocomplete function to apply when (DropDownList1.SelectedValue.ToString() == "JobTitle") applies. Not sure how to do this with Javascript/ Code behind. Any help is really appreciated!

Upvotes: 3

Views: 2383

Answers (1)

Jai
Jai

Reputation: 74738

You could do something like this:

if($('#<%= DropDownList1.ClientID %>').val() === 'JobTitle'){
    $("#<%= TextBox1.ClientID %>").autocomplete({ 
      // code
    });
}

Instead of load, you can initialize it on focus:

$("#<%= TextBox1.ClientID %>").on("focus", function(){
  if($('#<%= DropDownList1.ClientID %>').val() === 'JobTitle'){
      $(this).autocomplete({ 
        // code
      });
   }
});

Upvotes: 4

Related Questions