Search code examples
javascriptjquerydynamicselectable

To make an dynamic element selectable using jQuery


I am trying to make Item 1, Item 2 and Item 3 selectable.

HTML:

<div id="container">
   <ul id="outerUL">                   //static 
       <li id="outerLI">              //dynamic
           <ul id="innerUL">          //dynamic
              <li>Item 1</li>         //dynamic
              <li>Item 2</li>         //dynamic
              <li>Item 3</li>         //dynamic
           </ul>
       </li>   
   </ul>
</div>

jQuery:

$("#outerUL").delegate('li','click',function(event) {
        $(this).selectable();
}); 

I am not able to find out the error.


Solution

  • First cross check if you have the proper verison of jQuery and download it from here

    The problem with the code

    $("#outerUL").delegate('li','click',function(event) {
        $(this).selectable();
    });
    

    is that :

    $(this).selectable();
    

    will be called only when you click on some li child under outerUL. So your first click will not select any element rather it will just make the elements select ready.

    Second problem is in this html snippet:

     <ul id="outerUL">                   //static 
       <li id="outerLI">              //dynamic
           <ul id="innerUL">          //dynamic
              <li>Item 1</li>         //dynamic
              <li>Item 2</li>         //dynamic
              <li>Item 3</li>         //dynamic
           </ul>
       </li>   
    

    According to your javascript code, every element which is a children of #outerUL should be selectable. So the first time any children of #outerUL is clicked, $(this).selectable(); statement will be called which will make the child outerLIselectable. On the subsequent clicks, jQuery's selectable() function will be called and it will select the full outerLI element.

    I think this should solve your problem:

    $(function () {
    $("#innerUL").selectable();
    });
    

    It will make only the children of #innerUL selectable.