title: How to add a unique div ID in php 'foreach' loop and use that within JavaScript to show hide elements
body: <p>I have a simple php 'foreach' loop which works fine when there is only one loop. The php code displays a simple select box which shows or hides a div based on the selection value. The select box and div's are then repeated within each loop. The problem is that when there is more than one repeat of the code in the loop, the show/hide JavaScript does not work as the ID's are not unique, only the first in the loop works.</p>
  <p>How can I get this to work within a loop? Does the ID need to be unique or is there a better way to do this with Javascript?</p>
  <p><strong>PHP CODE:</strong></p>
  <pre class="lang-php prettyprint-override"><code>foreach ( $order-&gt;get_items() as $item_id =&gt; $item ) {
               
                  echo 'Service Area:';
                  echo '&lt;select id=&quot;serviceareaselect&quot;&gt;';
                  echo '&lt;option value=&quot;servicearea&quot;&gt;Select an Area...&lt;/option&gt;';
                  echo '&lt;option value=&quot;area1&quot;&gt;Area 1&lt;/option&gt;';
                  echo '&lt;option value=&quot;area2&quot;&gt;Area 2&lt;/option&gt;';
                  echo '&lt;/select&gt;';
               
                  // Service Area 1
                  echo '&lt;div id=&quot;area1&quot; class=&quot;servicearea&quot; style=&quot;display:none&quot;&gt;';
                  echo '&lt;input type=&quot;checkbox&quot; id=&quot;dur1&quot; name=&quot;dur1&quot; value=&quot;Dur1&quot;&gt;&lt;label for=&quot;vehicle1&quot;&gt;Dur1&lt;/label&gt;&lt;br&gt;';
                  echo '&lt;input type=&quot;checkbox&quot; id=&quot;dur2&quot; name=&quot;dur2&quot; value=&quot;Dur2&quot;&gt;&lt;label for=&quot;vehicle1&quot;&gt;Dur2&lt;/label&gt;&lt;br&gt;';
                  echo '&lt;/div&gt;';
                  
                  // Service Area 2
                  echo '&lt;div id=&quot;area2&quot; class=&quot;servicearea&quot; style=&quot;display:none&quot;&gt;';
                  echo '&lt;input type=&quot;checkbox&quot; id=&quot;aln1&quot; name=&quot;aln1&quot; value=&quot;Aln1&quot;&gt;&lt;label for=&quot;vehicle1&quot;&gt;Aln1&lt;/label&gt;&lt;br&gt;';
                  echo '&lt;input type=&quot;checkbox&quot; id=&quot;aln2&quot; name=&quot;aln2&quot; value=&quot;Aln2&quot;&gt;&lt;label for=&quot;vehicle1&quot;&gt;Aln2&lt;/label&gt;&lt;br&gt;';
                  echo '&lt;/div&gt;';
                  
  }
  </code></pre>
  <p><strong>JAVASCRIPT CODE:</strong></p>
  <pre class="lang-js prettyprint-override"><code>$(function()
  {
  $(&quot;#serviceareaselect&quot;).change(function(){
      $(&quot;.servicearea&quot;).hide();
      $(&quot;#&quot; + $(this).val()).show();
      });
  });
  </code></pre>