Why jquery function put value of li choosen in all input text?

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>jQuery Autocomplete from Database in JSP - Onlyxcodes</title>
        <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
        <style>
  
        </style>
    </head>
    
    <body>    
  

        <div class="container" style="overflow: auto;">
            <label>Enter Country Name</label>
            <input type="text" id="txtCountry" class="form-control" placeholder="enter country name">
            <div id="showList">
                <ul class="list-group">
                </ul>
            </div>
            <label>Enter age</label>
            <input type="text" id="txtCountry2" class="form-control" placeholder="Enter age">
            <div id="showList2">
                <ul class="list-group2">
                </ul>
            </div>
        </div>
    </body>
</html>

<script src="js/jquery-1.12.4-jquery.min.js" type="text/javascript"></script>
<script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script> 
<script type="text/javascript">
        $(document).ready(function(){
            $('#txtCountry').keyup(function(){
                $('#showList').show();
                var search=$('#txtCountry').val();
                if(search !=='' && search !==null)
                {    
                    $.ajax({ 
                       type:'POST',
                       url:'record.jsp',
                       data:'key='+search,
                       success:function(data)
                       {
                           $('#showList').html(data);
                       }
                    }); 
                }
                else
                {
                    $('#showList').html('');
                }
           $(document).on('click','li',function(){
               $('#txtCountry').val($(this).text());
           
  $('#showList').hide();
            });
    });
         $('#txtCountry2').keyup(function(){
                $('#showList2').show();
                var search=$('#txtCountry2').val();
                if(search !=='' && search !==null)
                {    
                    $.ajax({ 
                       type:'POST',
                       url:'record.jsp',
                       data:'key='+search,
                       success:function(data)
                       {
                           $('#showList2').html(data);
                       }
                    }); 
                }
                else
                {
                    $('#showList2').html('');
                }
           $(document).on('click','li',function(){
               $('#txtCountry2').val($(this).text());
           
  $('#showList2').hide();
            });
    });   
        });
</script>

record.jsp

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>

<%
    if(request.getParameter("key")!=null) //get "key" variable from jquery & ajax  part this line "data:'key='+search" and check not null 
    {
        String key=request.getParameter("key"); //get "key" variable store in created new "key" variable
        String wild="%" +key+ "%"; //remove "%" for use preparedstatement in query name like, and "key" variable store in "wild" variable for further use
         Connection conn;   
        Class.forName("com.mysql.jdbc.Driver");
                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/For_deces?useSSL=false","root","root");
   	   		

        try
        {
               PreparedStatement pstmt=null; //create statement

            pstmt=conn.prepareStatement("SELECT DISTINCT Lib_Wilaya FROM code_geographique WHERE Lib_Wilaya like ? "); //sql select query
            pstmt.setString(1,wild); //above created "wild" variable set in this
            ResultSet rs=pstmt.executeQuery(); //execute query and set in ResultSet object "rs".
           
            while(rs.next())
            {
                %>
                    <li class="list-group-item"><%=rs.getString("Lib_Wilaya")%></li>
                <%
            }
                conn.close(); //close connection
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
%>

I’m not seeing where you have a dropdown.

Rather than providing a small snippet of your code it’s best to provide a link to your live code so we can see all of it.
Also explain what it is you’re seeing versus what you expect to see.

i have edit it , thanks for answer

Unless the filter/autocomplete library you are using has some styles as well that you are not using what you are seeing is the default behavior of a normal page flow. Elements push each other as needed, just like paragraphs in a word document do not overlap, nor do elements by default.

You can use position: absolute to take the list out of the normal flow and let it overlap the other elements. You will likely need to apply some more styles as well to make it work.

Edit: It might also be that you are supposed to use a details or datalist element instead of a ul for the list.

1 Like

thank you this is worked , now when i choose one of the list it put the value in the two inputs , i dont understand why

<%@page contentType=“text/html” pageEncoding=“UTF-8”%>

jQuery Autocomplete from Database in JSP - Onlyxcodes
    </style>
</head>

<body>    


    <div class="container">
        <label>Enter Country Name</label>
        <input type="text" id="txtCountry" onkeyup="lookup(txtCountry,showList1,'record.jsp');" class="form-control" placeholder="enter country name">
        <div id="showList1" style="position: absolute ;">
            <ul class="list-group">
            </ul>
        </div>
        <label>Enter age</label>
        <input type="text" id="txtCountry2" onkeyup="lookup(txtCountry2,showList2,'record.jsp');" class="form-control" placeholder="Enter age">
        <div id="showList2" style="position: absolute ;">
            <ul class="list-group2">
            </ul>
        </div>
        <label>Enter dfg</label>
        <input type="text" id="txtCountry3" onkeyup="lookup(txtCountry3,showList3,'record.jsp');" class="form-control" placeholder="Enter age">
        <div id="showList3" style="position: absolute ;">
            <ul class="list-group2">
            </ul>
        </div>
    </div>
</body>

It is extremely hard to help you with this using what you have posted as we can not easily test it ourselves.

If I understand your question, are you sure the list is not just overlapping the input element so it looks like the list is “inside” the input element?

You can place absolutely positioned elements using the offsets top/right/bottom/left. And usually, you would put the absolutely positioned elements inside a relative position element as the parent.

thanks for replay lasjorg , my first question was about position and i have resolved it by using : style=“position: absolute ;”… my second question was about jquery , Why jquery function put value of li choosen in all input text?

Like I asked, are you sure the list is not just overlapping the input elements? Right-click the element and use Inspect to look at the DOM and see where the data is actually placed.

Are the lookup function arguments txtCountry and showList (with the number variations) variables or should they be strings? The lookup function seems to be targeting the showList elements so that is where the data should be placed.

Again, I really doubt I can be of much help without something I can actually test and see.

no its not overlapping , how can i send you my code to test it ?freecodecompt dont allow scripts as i see , i have tried every think without result , and i am newer in web application i really need to resolve this error ,

I think it is the last document click handler.

You seem to be setting the value of the input to $(this).text(). And this is the li so it would set the input element value (content) to the li text.

Example code
https://jsfiddle.net/Lx3onb0q/

Can you please also post the lookup function as code instead of an image?

i think yes , what i have to do to solve this error ?

Please do not post images of code, but the actual code. Images are not helpful as we can’t copy the code.

I mean that depends on what it is you are trying to do. What should happen when you click the li?

Capture3
the solution was cute simple , i added inputString=null; after put the value in textFieled calling the function , and this is worked :smiley: :grinning:

I’m not sure I understand what you are trying to do, but whatever if it does what you want then I guess it’s fine.

All you are doing is invalidating the selector by overwriting the content of the inputString function parameter.

If you just want to remove the listener after the first click you can use one() instead of on()

<input id="text" type="text">
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
let selector = "#text"

$(document).one('click', 'li', function() {
  $(selector).val($(this).text());
})
1 Like

this worked too , what i do is autocomplete of country ; that mean , i have countries in my database and on typing in textFieled the list of countries appear deponds of what he typed … thanks for your efforts lasjorg , you saved me :smiley: :smiley: :smiley: :heart_eyes: :heart_eyes:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.