2

I have a database containing table value values as:

Database: staff_details

    staffname

    Arun
    Suresh
    Ankita
    Tina

I wish to autocomplete textbox with values from database. For example, If I enter 'a' in textbox, then it should display all names from databse starting with letter 'a' only. Now it is displaying all names that contain 'a' letter. ie If I type 'a' in textbox, the list should contain 'Anikta' and 'Arun' only.

My current list contain Arun,Anikta and Tina , when I enter letter 'a' in textbox.

How to display values from database starting with entered letter in textbox as a list

What I have tried:

          <label for="validationDefaultUsername">Authors </label>     
           <% 
           Connection con=null;                
           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");    

           PreparedStatement ps1= con.prepareStatement("select staffname from staff_details ");              
           ResultSet rs=ps1.executeQuery();           
           %>      
          <input type="text" class="form-control"  name="prepared_by" id="auth" placeholder="Author " list="a_data" id="auth"   required>
          <%

           %>      
          <datalist id="a_data">
               <%while(rs.next())
                    { %>                   
                        <option value="<%= rs.getString(1) %> "> </option>
                        <%
                    }
                    %>
          </datalist>
               </div>
codeuser
  • 179
  • 2
  • 11

1 Answers1

0

You need to use LIKE operator in your query ,So your code will be like below :

        <% 
           Connection con=null;                
           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");    

           PreparedStatement ps1= con.prepareStatement("select staffname from staff_details where staffname  LIKE ? ");  
            ps1.setString(1, search + "%");
                           //^ passing value to placeholder  & here "%"<- can be any letter   
           ResultSet rs=ps1.executeQuery();           
           %>      

Also , refer my answer for doing this with ajax .

Swati
  • 28,069
  • 4
  • 21
  • 41