Reputation: 346
I have jquery UI accordion divs under foreach loop and inside each div i have two buttons. One is add button. When add button is clicked, it is swapped by a dropdown button which using select2 jquery UI. When a value is selected from dropdown, it is saved to database using ajax call.
My issue is that this scenerio is working only for the first accordion div. But for other divs jquery is disabled because id is repeated in foreach loop. Please help if anyone has better way to do it.
Note: I am using codeigniter.
<div id="accordion">
<?php foreach ($groups as $grp): ?>
<h3><?php echo $grp->name; ?></h3>
<div>
<div class="form-group" id="swapper-two" style="display:none;">
<select class="populate placeholder s2_service" id="getser" name="">
<option value="">-- Select a value --</option>
<option value=""> One </option>
<option value=""> Two </option>
<option value=""> Three </option>
</div>
<div id="swapper-one" style="display:block" >
<a href="javascript:swapping('swapper-one','swapper-two')" ><button type="button" class="btn btn-default btn-xs btn-label-left"><i class="fa fa-plus"></i></button></a>
</div>
</div>
</div>
<?php endforeach; ?>
Jquery is here:
function swapping(div1,div2) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
d1.style.display = "none";
d2.style.display = "block";
}
Upvotes: 1
Views: 106
Reputation: 9060
To make the code universal, change the id into class. Try this solutions
<div id="accordion">
<?php foreach ($groups as $grp): ?>
<h3><?php echo $grp->name; ?></h3>
<div>
<div class="form-group" class="swapper-two" style="display:none;">
<select class="populate placeholder s2_service" id="getser" name="">
<option value="">-- Select a value --</option>
<option value=""> One </option>
<option value=""> Two </option>
<option value=""> Three </option>
</div>
<div class="swapper-one" style="display:block" >
<a href="#"><button type="button" class="btn btn-default btn-xs btn-label-left myBtn"><i class="fa fa-plus"></i></button></a>
</div>
</div>
</div>
<?php endforeach; ?>
Jquery is here:
<script>
$(function(){
$(document).on('click', '.myBtn', function(e){
e.preventDefault();
$(this).prev().show(); // show swapper two
$(this).parent().hide(); // hide swapper one
})
})
</script>
P/s : im not sure you make the closest foreach is right or not. Seem like outside the parent accordian div
Upvotes: 0
Reputation: 26153
You use the same id name for all groups of div that results in working just first one. If $grp->name is unique, change swapper
in id and in fuction call by this name <?= $grp->name ?>
Upvotes: 1