Wouter Wouter - 2 months ago 25
CSS Question

Javascript, CSS - Modal id while loop unique id

Hey All i have the following code which works perfect but i also want to use the same concept inside a for each loop. This wont work because there is no unique identifier. How can i solve this? Below is my code (with the for each loop)

.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 250px; /* Location of the box */
left: 680;
top: 0;
width: 35%; /* Full width */
}

.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
min-height: 250;
}

.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close :hover,
.close :focus {
color: #000;
text-decoration: none;
cursor: pointer;
}


Then i have some php code

foreach ($myarray as $my_array) {

Select table etc


echo " <div class='col-sm-4 hides'> <button style='background-color: Transparent; border: none; padding: 0px 0px;' color='white' onclick=\"selected_comp('" . $received1['id'] . "','" . $comp_row['id'] . "','" . $comp_row['functions'] . "','" . preg_replace("/\r|\n/", "", $comp_row['comments']) . "')\"> <b>" . $comp_row['functions'] . "</b><br>";



echo "</button>";
if (strlen($comp_row['comments']) > 100){
echo "
<a href='javascript:void(0);' id='showall3'>Volledige beschrijving. </a>
<div id='myModal3' class='modal'>
<div class='modal-content'>
<span id='close3' class='close'>×</span>
<p>
<b> " . $comp_row['functions'] . " </b><br>
" . nl2br($comp_row['comments']). "
</p>
</div>
</div>
";
}


And i got some javascript code to show the modal (and hide)

var modal3 = document.getElementById('myModal3') ;
$('#close3').click(function(){
modal3.style.display = 'none';
});
$('#showall3').click(function(){
modal3.style.display = 'block';
});

Answer

Change the ids to classes,get the modal body selecting the element relative to the clicked element using closest() & next(), use show/hide to toggle the display property

echo "  
<a href='javascript:void(0);' class='showAll'>Volledige beschrijving. </a>
    <div  class='modal myModal'>
    <div class='modal-content'>
        <span class='close'>×</span>
        <p>
        <b> " . $comp_row['functions'] . " </b><br>
         " . nl2br($comp_row['comments']). "
        </p>
      </div>
    </div>
    "; 

$('.close').click(function(){
  $(this).closest('.myModal').hide();
});
$('.showAll').click(function(){
  $(this).next().show();
});