0

I have the following HTML and Javascript code. I am trying to make a search suggestion system. The list-items in the unordered-list 'search_suggest' are retrieved dynamically using ajax as the user types in the input box 'site_search' and inserted.

<form name="search_site_form" method="get" action="search.php">
        <input id="site_search" name="q" class="search_input input" autocomplete="off" value="Search the site" type="text"/>

    <ul id="search_suggest">
    </ul>
    <input value=" " type="submit" class="search_submit"/>
    <script type="text/javascript">
    <!--
        $("ul#search_suggest>li").click(function(){ 
        alert('123');
    });
    //-->
    </script>
</form>

Clicking on the list items in search_suggest however is not triggering the click function. Any idea why?

5 Answers 5

6

You need to bind the click event to the list items after they have been added to the page.

Before any list items get added to the page, the expression $("ul#search_suggest>li") finds nothing, so no elements get bound to the click event.

You need to use .live that will:

Attach a handler to the event for all elements which match the current selector, now and in the future

Like the following:

<script type="text/javascript">
<!--
    $("ul#search_suggest>li").live('click', function(){ 
    alert('123');
});
//-->
Sign up to request clarification or add additional context in comments.

Comments

1

Your script is running once, binding the onclick action to non-existent <li> elements. You will need to build into your AJAX script something that will add the onclick to each <li> element as they are added to the DOM.

Comments

0

use the jQuery.live();

 <script type="text/javascript">
    <!--
        $("ul#search_suggest>li").live('click', function(){ 
        alert('123');
    });
    //-->
    </script>

Comments

0

Use

$("ul#search_suggest+input").click(function(){ 
        alert('123');
    });

Here the input tag is the next sibling of an ul with id earch_suggest
+ is the jQuery Next Sibling Selector

The selector "ul#search_suggest>li" means find the li which is the child of the ul with id search suggest.
> is the jQuery Child Selector

Comments

0

Add empty li or li with values into and test it like this <ul id="search_suggest"> <li></li> </ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.