javascriptjqueryhtmllistjquery-ui-selectable

Using Jquery Selectable IDs multiple times


I am completely new to jquery and I am trying to make two lists where every item is selectable.

Here is my Code:

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI selectable-1</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <style>
      li{
         display: inline-block;
         padding: 20px;
         border: solid black;
         cursor: pointer;
      }

      .ui-selected{
         background-color: green;
         color: white;
      }
      </style>
      <script>
         $(function() {
            $("#selectable").selectable();
         });
      </script>
   </head>

   <body>
      <ol id = "selectable">
         <li>Product 1</li>
         <li>Product 2</li>
         <li>Product 3</li>
         <li>Product 4</li>
         <li>Product 5</li>
         <li>Product 6</li>
         <li>Product 7</li>
      </ol> 

      <ol id = "selectable">
         <li>Product 1</li>
         <li>Product 2</li>
         <li>Product 3</li>
         <li>Product 4</li>
         <li>Product 5</li>
         <li>Product 6</li>
         <li>Product 7</li>
      </ol> 
   </body>
</html>

It seems like an ID of a list cant be used twice since the items in the first list are selectable and the items in the second list are not selectable.

Lets say I have many more lists. There must be a more efficient way to make all items in all lists selectable than writing

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

for every list ID I have.

I googled a lot and couldn't find a solution.

For this example I just used two lists so its not overloaded but I need to use a tons of list in my HTML template which is dynamically created and I need to make all items selectable in every list.


Solution

  • You should not use an ID more than once across an entire site. The whole point of ID is that it's supposed to be unique.

    To target multiple elements, use classes. The way to think about classes is that they "classify" the type, or behaviour, of an element. Since you're trying to classify each list as "selectable", you can use a .selectable class.

    <ol class="selectable">
    

    Javascript

    $('.selectable').selectable();