Replace Input Value by click on AJAX search value

Issue

I been able to return result value from php sql but by click on result value I cannot set the input value, how to do that, Thank you.

script

    $(document).ready(function(){
        $('#input').on("keyup input", function(){
            var input = $(this).val();
            var result = $(this).parent().parent().next(".result");
            if(input.length){
                $.get("backend-search.php", {term: input}).done(function(data){
                    result.html(data);
                });
            } else{
                result.empty();
            }
        });

        $(document).on("click", ".result p", function(){
            $(this).prev().children().children('input[type="text"]').val($(this).text());
            result.empty();
        });
    });

HTML

 <div>

        <div>
            <ol style="list-style: none;">
                <li>
                    <input id='input' type="text" autocomplete="off" placeholder="Search..." />
                </li>
            </ol>

            <div class="result"></div>
        </div>


    </div>

Solution

Assuming your set of results looks something like this:

<div class='result'>
    <p></p>
    <p></p>
    <p></p>
</div>

Then work through what this selector is doing if you click, say, the 2nd <p>:

$(this).prev().children().children('input[type="text"]')
  • .prev() will target the "immediately preceding sibling". For our example case that would select the first <p>;

  • Next, .children() searches down the DOM tree for children of that <p>. You haven’t shown us what that HTML looks like but most likely it is plain text, with no children. Even if it has some (eg <span>), it isn’t going to help us get back to the <input>, this is the wrong direction.

You really need to search back up the DOM first, until we get to something that includes the input, and then back down.

$(this).parent().parent().find('input')
  • The first .parent() will select the <div class='result'>;

  • The 2nd will target the parent <div> which includes both your input and your results;

  • The .find() will search down from that node looking for an input;

You can simplify this, and make it a little bit safer from future HTML changes, by adding a class to the element which contains both input and results. In a comment you mention you plan to have multiple sets of them, so maybe each "set" could be called a "search":

<div class='search'>
    <ol> ... <input> ... </ol>
    <div class='result'> ... </div>
</div>

<div class='search'>
    <ol> ... <input> ... </ol>
    <div class='result'> ... </div>
</div>

Now it is much easier to target the right elements using .closest():

$(this).closest('search').find('input')

Answered By – Don't Panic

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.