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.
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?
PHP CODE:
foreach ( $order->get_items() as $item_id => $item ) {
echo 'Service Area:';
echo '<select id="serviceareaselect">';
echo '<option value="servicearea">Select an Area...</option>';
echo '<option value="area1">Area 1</option>';
echo '<option value="area2">Area 2</option>';
echo '</select>';
// Service Area 1
echo '<div id="area1" class="servicearea" style="display:none">';
echo '<input type="checkbox" id="dur1" name="dur1" value="Dur1"><label for="vehicle1">Dur1</label><br>';
echo '<input type="checkbox" id="dur2" name="dur2" value="Dur2"><label for="vehicle1">Dur2</label><br>';
echo '</div>';
// Service Area 2
echo '<div id="area2" class="servicearea" style="display:none">';
echo '<input type="checkbox" id="aln1" name="aln1" value="Aln1"><label for="vehicle1">Aln1</label><br>';
echo '<input type="checkbox" id="aln2" name="aln2" value="Aln2"><label for="vehicle1">Aln2</label><br>';
echo '</div>';
}
JAVASCRIPT CODE:
$(function()
{
$("#serviceareaselect").change(function(){
$(".servicearea").hide();
$("#" + $(this).val()).show();
});
});