I've been staring at code all day, and I just can't seem to find what im looking for, I know how to do this with PHP but I'm new to dynamic stuff.
This code is inside a loop that is generated by a database. The dropdown items are fixed, but each individual is inside a database. I want to be able to choose the next drop down box selections based on the first one. This code works but not for each individual in the loop. Each item in the loop just updates the top one.
<div class="grid-container-fluid" style="margin-bottom: 25px;">
<div class="grid-container" style="font-family: 'Roboto Condensed', sans-serif;">
<div class="grid-x align-center">
<div class="large-10 cell">
<div class="grid-x">
<?php
if ($result->num_rows > 0) {
echo '<div class="large-12 cell">';
echo '<p style="font-family: Roboto Condensed, sans-serif; letter-spacing: 2px; font-weight: bold; line-height:1; font-size: 30px;">ADMIN PANEL:</p>';
echo '<p style="font-family: Roboto Condensed, sans-serif; font-size: 20px;">Income: $'.$total.'/mo<br>Program Value: $'.$value.'/person</p>';
echo '</div>';
echo '<div class="large-12 hide-for-small-only cell" style="border-bottom: 3px black solid; padding-bottom: 5px;">';
echo '<div class="grid-x">';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">NAME</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">EMAIL</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">PROGRAM</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">PLAN</p>';
echo '</div>';
echo '<div class="medium-2 small-6 cell">';
echo '<p align="left" style="margin: 0;">STATUS</p>';
echo '</div>';
echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
echo '<p style="margin:0; text-align: center">';
echo '<i class="fi-wrench"></i>';
echo '</p>';
echo '</div>';
echo '</div>';
echo '</div>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="large-12 cell" style="border-bottom: 1px black solid; padding: 5px;">';
echo '<div class="grid-x align-middle">';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["name"].'" name="name">';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["email"].'" name="email">';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program" onChange="changecat(this.value, '.$value.');">';
echo '<option value="" disabled selected>'.$row["program"].'</option>';
echo '<option value="Hockey">Hockey</option>';
echo '<option value="Fundamentals">Fundamentals</option>';
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan">';
echo '<option value="" disabled selected>'.$row["plan"].'</option>';
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = {
Hockey: ["Off Season", "Pre Season", "In Season"],
Fundamentals: ["Phase 1"],
}
function changecat(value) {
if (value.length == 0) document.getElementById("plan").innerHTML = "<option></option>";
else {
var catOptions = "";
for (planId in programsByplan[value]) {
catOptions += "<option>" + programsByplan[value][planId] + "</option>";
}
document.getElementById("plan").innerHTML = catOptions;
}
}
</script>
<?php
echo '<div class="medium-2 small-12 cell">';
echo '<div class="grid-x align-middle">';
echo '<div class="small-6 cell">';
echo '<select style="margin: 0; height: auto; border: 0;" name="week">';
echo '<option value="'.$row["week"].'">' . 'Week ' . $row["week"] . '</option>';
echo '<option value="1">Week 1</option>';
echo '<option value="2">Week 2</option>';
echo '<option value="3">Week 3</option>';
echo '<option value="4">Week 4</option>';
echo '<option value="5">Week 5</option>';
echo '<option value="6">Week 6</option>';
echo '<option value="7">Week 7</option>';
echo '<option value="8">Week 8</option>';
echo '<option value="9">Week 9</option>';
echo '<option value="10">Week 10</option>';
echo '<option value="11">Week 11</option>';
echo '<option value="12">Week 12</option>';
echo '<option value="13">Week 13</option>';
echo '<option value="14">Week 14</option>';
echo '<option value="15">Week 15</option>';
echo '</select>';
echo '</div>';
echo '<div class="small-6 cell">';
echo '<select style="margin: 0; height: auto; border: 0;" name="day">';
echo '<option value="'.$row["day"].'">' . 'Day ' . $row["day"] . '</option>';
echo '<option value="1">Day 1</option>';
echo '<option value="2">Day 2</option>';
echo '<option value="3">Day 3</option>';
echo '<option value="4">Day 4</option>';
echo '</select>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
echo '<p style="margin:0; text-align: center">';
echo '<input style="font-size: 12px;" class="expanded button nav" type="submit" value="Update" name="submit" id="submit"/>';
echo '</p>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
</div>
</div>
</div>
</div>
</div>
I know it needs a unique id, I just can't figure out where.
Something like this:
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >';
echo '<option value="" disabled selected>'.$row["program"].'</option>';
echo '<option value="Hockey">Hockey</option>';
echo '<option value="Fundamentals">Fundamentals</option>';
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
echo '<option value="" disabled selected>'.$row["plan"].'</option>';
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = {
Hockey: ["Off Season", "Pre Season", "In Season"],
Fundamentals: ["Phase 1"],
}
$('select[name="program"]').change(function(){
var program = $(this).val();
var plan_id = $(this).prop('id').replace('program', 'plan');
if(programsByplan[program]){
var options = [];
$.each(programsByplan[program], function(i,v){
options.push('<option value="'+v+'">'+v+'</option>');
});
$('#'+plan_id).html(options.join("\n"));
}else{
//or, do somkind of error recovery here.
$('#'+plan_id).html('<option value="">No Plans</option>');
}
});
</script>
I would get rid of the onChange, I'm also making heavy use of jQuery, but the question is tagged with it.
So on the change of any select with the name program (which we haven't changed, so they all have the same name) we trigger the event callback. You could also do this part with a class, of course.
In the callback we get the value selected in the current select, then we check that it exists in programsByplan (which it always should) but doesn't hurt to check.
Then we convert the program id program-'.$row['id'].' to plan-'.$row['id'].'. Now we know which plan select to change. I prefer using an array to add the options, but you could do the += thing. And then it's a simple matter to replace them, now that we know the plan elements id, with .html().
I haven't tested this but it should be pretty close. The big thing is setting yourself up to succeed by having the id easy to correlate, or in other words easy to find the right plan element for the changed program element.
I am also assuming you have a $row['id'] that is at least unique to the loop that generates these.
Update
But how do I get the options to show up on page load when the program/plan is proper from the database
I would further change it like this:
//outside of the loop define your data
$programsByplan = [
'Hockey' => ["Off Season", "Pre Season", "In Season"],
'Fundamentals' => ["Phase 1"],
];
//inside the loop
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >';
foreach($programsByplan as $program => $plans){
//$selected = $row["program"] == $program ? 'disabled selected' : '';
$selected = $row["program"] == $program ? 'selected="selected"' : '';
echo '<option value="'.$program.'" '.$selected.'>'.$program.'</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
foreach($programsByplan[$row["program"]] as $plan){
//$selected = $row["plan"] == $plan ? 'disabled selected' : '';
$selected = $row["plan"] == $plan ? 'selected="selected"' : '';
echo '<option value="'.$plan.'" '.$selected.'>'.$plan.'</option>';
}
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = <?php echo json_encode($programsByplan); ?>;
//... other code
Here we are adding $programsByplan in PHP, then with json_encode we can add the same array to Javascript, which is awesomeness. Hopeful this works
var programsByplan = <?php echo json_encode($programsByplan); ?>;
Sometimes it can take a bit of fiddling to, but it has huge benefits in maintainability for the code. Because you are using only one authoritative source for the data for that. As opposed to it being spread everywhere. A side benefit of this is, if you go and make the programs and plans as two tables with a Many to One relationship you could put those in the DB and easily update the code by building that array. See if the data is just spread out hard coded then it's difficult to make changes like that later.
It also lets us fix a few of the other issues you had with building the selects originally, and just simplifies the code. One big issue was removing the value on the selected items, and having duplicate items.
echo '<option value="" disabled selected>'.$row["program"].'</option>';
You are actually removing the value here, which is probably not what you want. I am also not sure about the disabled bit, so I just left that in. Maybe that was just there to fix the selection issues from initializing it? Anyway I put that part in a comment. I've always done selected like this:
$selected = $row["program"] == $program ? 'selected="selected"' : '';
It's probably the "old-school" way of doing it but it always worked for me.
Anyway, and obviously if we try to get the value of the selected option and its value has been removed, it probably wont work out to good. Not to mention there is no way to "know" what that is to remove the option with the same value when it's just hard coded in like it was and so you'll wind up with a duplicate option for it.
This should fix most of that, but this is all done in my head, so hopefully it all works out like I am thinking it should. The theory is sound anyway.
You can test it in this sandbox:
http://sandbox.onlinephpfunctions.com/code/077c8a988697122549713ede9c305bf4f7620ed9
using (As canned data for a row.)
$row = [
'id' => 1,
'program' => 'Hockey',
'plan' => 'Off Season'
];
Which outputs:
<div class="medium-auto small-12 cell" style="padding:2px;">
<select style="margin: 0; height: auto; border: 0;" name="program" id="program-1" >
<option value="Hockey" selected="selected">Hockey</option>
<option value="Fundamentals" >Fundamentals</option>
</select>
</div>
<div class="medium-auto small-12 cell" style="padding:2px;">
<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-1">
<option value="Off Season" selected="selected">Off Season</option>
<option value="Pre Season" >Pre Season</option>
<option value="In Season" >In Season</option>
</select>
</div>
As you can see we have program-1 and plan-1 our ID's, then both selects have the proper element with selected="selected"
Update2
To handle cases where no data was previously selected for the program.
For the first loop above I would add this
//echo <select ...
echo '<option value="" > - Please select a program - </option>';
//foreach( ...
Do it before the loop and after the opening for the <select. Then for the second loop I would disable the second select, until they make a choice in the first.
$disabled = empty($row["program"]) ? 'disabled="disabled"': '';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'" '.$disabled.'>';
And then in the Javascript
$('select[name="program"]').change(function(){
var program = $(this).val();
if(program == '' ) return; //exit on empty selection
var plan_id = $(this).prop('id').replace('program', 'plan');
//enable the select if disabled.
$('#'+plan_id).attr('disabled',false);
Then you may just want to check before saving it that they selected a program etc. etc..
Update3
For any Javascript issues always use the debug window in the browser (f12) then click on console. Then in your code you can just do like
console.log(var);
And it will print that value in the console. It's simular to PHP's var_export, print_r or var_dump etc...
So I would start with this
<script>
var programsByplan = <?php echo json_encode($programsByplan); ?>;
console.log(programsByplan);
$('select[name="program"]').change(function(){
var program = $(this).val();
console.log(program);
var plan_id = $(this).prop('id').replace('program', 'plan');
console.log(programsByplan[program]);
if(programsByplan[program]){
var options = [];
$.each(programsByplan[program], function(i,v){
options.push('<option value="'+v+'">'+v+'</option>');
});
$('#'+plan_id).html(options.join("\n"));
}else{
//or, do somkind of error recovery here.
$('#'+plan_id).html('<option value="">No Plans</option>');
}
});
</script>
And so on and see what the values are. That's probably the best way.
Cheers.
Related
I’m working on a php snippet and i made a table. I tried putting a td tag inside but when i do this, a lot disappears. This is a piece of my code:
//Use the functions of the client, the params of the function are in
//the associative array
$params = array('customerid' => '1532');
$response = $soapclient->ca_customer_products($params);
echo '<table><tbody><tr><th>Product</th><th>Naam</th> <th>Prijs</th><th>Qte</th></tr>';
echo '<table style="border-style: solid; border-width:1px;">';
foreach($response->list->element as $product) {
if($product->stock > 0) {
echo '<tr>';
echo '<td style="display: flex; border: 1px solid black;">';
//echo '<td>';
echo '<img src="' . $product->url . '" class="php_image" style="width: 15%; height: 15%;"/>';
//echo '<img style="width: 15%;">';
//echo '</td>';
print_r($product->description);
echo "<p style='color:green;'>".$product->price1."</p>";
echo "<p style='color:red; text-decoration: line-through'>".$product->price2."</p>";
print_r($product->price1);
print_r($product->price2);
print_r($product->stock);
echo '</tr>';
}
}
echo '</tbody></table>';
The code behind the // is where i tried to put the td tag but when i put it there, the images that normally appear go blank and when i inspect my code there is a lot of other code that also disappears. What am i doing wrong here?
Thank you for your help!
First I can see a problem with these lines :
echo '<table><tbody><tr><th>Product</th><th>Naam</th> <th>Prijs</th><th>Qte</th></tr>';
echo '<table style="border-style: solid; border-width:1px;">';
Because you just close your first TABLE at the end, but not the other inside :
echo '</tbody></table>';
There are some inconsistency of your <td> to <th>. You can have a look below
$params = array('customerid' => '1532');
$response = $soapclient->ca_customer_products($params);
echo '<table style="border-style: solid; border-width:1px;">
<thead>
<tr>
<th>Product</th>
<th>Naam</th>
<th>Prijs</th>
<th>Qte</th>
</tr>
</thead><tbody>';
foreach($response->list->element as $product) {
if($product->stock > 0) {
echo "<tr>
<td style='display: flex; border: 1px solid black;'>
<img src='$product->url' class='php_image' style='width: 15%; height: 15%;'/>
</td>
<td>Your product name</td>
<td>$product->description</td>
<td>
<p style='color: green;'>$product->price1</p>
<p style='color: red;'>$product->price</p>
</td>
<td>$product->stock</td>
</tr>";
}
}
echo '</tbody></table>';
?>
There's a lot problems with the code. From what i can see in your code, you have a table inside a tbody and at the end closed only one table.
Secondly you're also trying to put a td inside another td which is not the right thing to do. Check out mozilla developer website for more information on using HTML tables.
//Use the functions of the client, the params of the function are in
//the associative array
$params = array('customerid' => '1532');
$response = $soapclient->ca_customer_products($params);
echo '<table style="border-style: solid; border-width:1px;"><tbody><tr><th>Product</th><th>Naam</th> <th>Prijs</th><th>Qte</th></tr>';
foreach($response->list->element as $product) {
if($product->stock > 0) {
echo '<tr>';
echo '<td style="display: flex; border: 1px solid black;">';
//echo '<td>';
echo '<img src="' . $product->url . '" class="php_image" style="width: 15%; height: 15%;"/>';
//echo '<img style="width: 15%;">';
//echo '</td>';
print_r($product->description);
echo "<p style='color:green;'>".$product->price1."</p>";
echo "<p style='color:red; text-decoration: line-through'>".$product->price2."</p>";
print_r($product->price1);
print_r($product->price2);
print_r($product->stock);
echo '</td></tr>';
}
}
echo '</tbody></table>';
You are not closing your tags correctly. Also checkout the docs just as #christopher_bincom has mentioned.
in this php code i have foreach loop create textarea with checkbox for each statement
i wanna to enable textarea if his checkbox is checked
but they have same id
<?php
foreach($Arows as $row){
echo '<tr class="row">
<th class="col-sm-12"><h4>'.$row['Type_A'].'</h4></th>
</tr>';
$stmt3 = $con->prepare("SELECT * FROM sous_analyse WHERE Id_A =".$row['Id_A']);
$stmt3->execute();
$SArows = $stmt3->fetchAll();//Analyse rows
foreach($SArows as $Srow){
echo '<tr class="row">
<td class="col-sm-4">'.$Srow['Parameter'].'</td>
<td class=" col-sm-5"><input type="text" class="form-control col-xl-12 border-secondary" name="Fonctionnalite" placeholder="RESULTATS" required=""></td>
<td class="col-sm-3 text-center">'.$Srow['Normal'].'</td>
</tr>';
}
echo '<tr class="row">
<th class="col-sm-12">
<div class="input-group">
<span class="input-group-addon form-check">
<span class="checkbox-custom checkbox-default">
<input type="checkbox" class="icheckbox-grey" id="inputUnchecked" name="inputUnchecked">
<label for="inputUnchecked"></label>
</span>
</span>
<textarea class="form-control" id="textareaDefault" rows="3" style="margin-top: 0px; margin-bottom: 0px; height: 60px;" disabled></textarea>
</div>
</th>
</tr>';
}
?>
i use this script but is working in first textarea
<script >
$(document).ready(function() {
$("#inputUnchecked").on('click', function() {
if($(this).is(':checked')){
$("#textareaDefault").prop('disabled',false);
} else {
$("#textareaDefault").prop('disabled',true);
}
alert("fdg");
})
});
</script>
Expanding on my comment, you will want to adjust your PHP. This is easily done with a counter ($c).
<?php
foreach($Arows as $row){
$html = "";
$html .= '<tr class="row">'."\r\n";
$html .= '<th class="col-sm-12"><h4>'.$row['Type_A'].'</h4></th>'."\r\n";
$html .= '</tr>'."\r\n";
$stmt3 = $con->prepare("SELECT * FROM sous_analyse WHERE Id_A =".$row['Id_A']);
$stmt3->execute();
$SArows = $stmt3->fetchAll();
$c = 1;
foreach($SArows as $Srow){
$html .= '<tr class="row">'."\r\n";
$html .= '<td class="col-sm-4">'.$Srow['Parameter'].'</td>';
$html .= '<td class=" col-sm-5"><input type="text" class="form-control col-xl-12 border-secondary" name="Fonctionnalite" placeholder="RESULTATS" required=""></td>';
$html .= '<td class="col-sm-3 text-center">'.$Srow['Normal'].'</td>';
$html .= '</tr>';
}
$html .= '<tr class="row">';
$html .= '<th class="col-sm-12">';
$html .= '<div class="input-group">';
$html .= '<span class="input-group-addon form-check">';
$html .= '<span class="checkbox-custom checkbox-default">';
$html .= '<input type="checkbox" class="icheckbox-grey" id="inputUnchecked-$c" name="inputUnchecked">';
$html .= '<label for="inputUnchecked-$c"></label>';
$html .= '</span></span>';
$html .= '<textarea class="form-control" id="textareaDefault-$c" rows="3" style="margin-top: 0px; margin-bottom: 0px; height: 60px;" disabled></textarea>';
$html .= '</div></th></tr>';
echo $html;
$c++;
}
?>
Your JavaScript can then use the ID since it is unique or can simply be relative to nearby elements.
$(function() {
$("[id^='inputUnchecked-']").on('click', function() {
if($(this).is(':checked')){
$(this).parent().parent().find("[id^='textareaDefault-']").prop('disabled',false);
} else {
$(this).parent().parent().find("[id^='textareaDefault-']").prop('disabled',true);
}
alert("fdg");
})
});
I am trying to show a dummy image from - Font awesome- when the picture is not set.
You can see my code it shows the image if there is one but when there isn't one it needs to set the dummy pic from awesomefont. tried pasting this <i class="fas fa-user-circle"></i> in the else but that isn't working. can anyone please help me?
<?php
$onderrwerp = $app->get_onderwerpen();
foreach($onderrwerp as $onderwerp){
echo '<div class="well well-sm">';
if(file_exists('assets/images/profielfotos/'.$onderwerp['klant_id'])) {
echo '<img class="img-circle" src="/assets/images/profielfotos/'.$onderwerp['klant_id'].'/'.$onderwerp['foto'].'" />';
} else {
}
echo '<b> '.$onderwerp['onderwerpnaam'].'</b>';
echo ' - ' . $onderwerp['voornaam'] . ' ' . $onderwerp['achternaam'];
echo '</div>';
}
?>
update
this worked for me! I changed it a little with the font-size. The only problem I have is that it isnt aligned great. As you can see on the pic the text next to the picture on the first one is nice but the second and 3e are a little but lower? how to fix that?
<script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js" integrity="sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl" crossorigin="anonymous"></script>
<?php
$onderrwerp = $app->get_onderwerpen();
foreach($onderrwerp as $onderwerp){
echo '<div class="well well-sm">';
if(file_exists('assets/images/profielfotos/'.$onderwerp['klant_id'])) {
echo '<img class="img-circle" src="/assets/images/profielfotos/'.$onderwerp['klant_id'].'/'.$onderwerp['foto'].'" />';
} else {
echo '<i style="font-size: 2.5em;" class="fas fa-user-circle"></i>';
}
echo '<b> '.$onderwerp['onderwerpnaam'].'</b>';
echo ' - ' . $onderwerp['voornaam'] . ' ' . $onderwerp['achternaam'];
echo '</div>';
}
?>
how it looks like now
You may be missing the required js file that's why it's not showing.
Getting Started
Try:
<script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js" integrity="sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl" crossorigin="anonymous"></script>
<?php
$onderrwerp = $app->get_onderwerpen();
foreach($onderrwerp as $onderwerp){
echo '<div class="well well-sm">';
if(file_exists('assets/images/profielfotos/'.$onderwerp['klant_id'])) {
echo '<img class="img-circle" src="/assets/images/profielfotos/'.$onderwerp['klant_id'].'/'.$onderwerp['foto'].'" />';
} else {
echo '<i style="font-size: 6em;" class="fas fa-user-circle"></i>';
}
echo '<b> '.$onderwerp['onderwerpnaam'].'</b>';
echo ' - ' . $onderwerp['voornaam'] . ' ' . $onderwerp['achternaam'];
echo '</div>';
}
?>
You can put the font icon in else part and it should work perfectly.
I think your if statement isn't allowing you to goto else. just update the if condition like this:
$foto = '/assets/images/profielfotos/'.$onderwerp['klant_id'].'/'.$onderwerp['foto'].' 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($foto)) {
echo '<img class="img-circle" src="'.$foto.'" />';
}
else{
echo '<i class="fas fa-user-circle"></i>'
}
For your second problem:
You can write CSS class and use it in the parent, in your case it'll be <div class="well align-children"> :
.align-children{
line-height: 40px; /* depending on the size of your icon */
display: inline-block;
vertical-align: middle;
}
You can use the styling on html document with this:
<style>
.align-children{
line-height: 40px; /* depending on the size of your icon */
display: inline-block;
vertical-align: middle;
}
</style>
My intention is to display the content(which is stored in mysql) if the picture is clicked.
<?php
$query = "SELECT * FROM pet where pet_cat = 'D' ORDER BY petid ";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['petname'] = $row['petname'];
$_SESSION['petdesc'] = $row['petdesc'];
$_SESSION['petimg'] = $row['petimg'];
echo '<li style="
padding-right: 20px;
padding-left: 20px;">';
echo '<a style= "cursor: pointer;"onclick= "document.getElementById(\'dogmod\').style.display=\'block\'">';
echo '<img src="data:image/jpeg;base64,'.base64_encode($_SESSION['petimg'] ).'" />';
echo '<h4>';
echo $_SESSION['petname'] ;
echo '</h4>';
include 'desca.php';
echo '</a>';
echo '</li>';
}
?>
The modal only display one content and that is the first content of the first picture.(sorry for bad english )
This is the code of my modal:
<div id="dogmod" class="modal">
<center>
<form class="modal-content animate" style="margin: 0; padding-left:50px; padding-right:50px; padding-bottom:50px;">
<div class="imgcontainer">
<span onclick="document.getElementById('dogmod').style.display='none'" class="close" title="Close">×</span>
<h1 align=center>Description</h1>
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode($_SESSION['petimg'] ).'" style="margin-top:50px;float:left; margin-right:50px;"/>'; ?>
<h1 style="margin-top:50px;margin-bottom:50px">
<?php echo $_SESSION['petname'] ;?>
</h1>
<p style="margin-bottom:50px;">
<?php echo $_SESSION['petdesc'] ;?>
</p>
<input type="button" value="Back" onclick=location.href='doga.php' class="button_1" style=" width: auto;padding: 10px 18px; background-color: #f44336; border:0px; color:white;">
<h2> </h2>
</form>
</center>
<script>
// Get the modal
var modal = document.getElementById('dogmod');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</div>
The problem is that you are generating many modals with the same "id".
What happens in this case is that you will be displayed only the last image in the table.
Generate your modal id dynamically.
Use php and add an affix to the id attribute of the modal and call that one in your onclick event.
Here is how you do it:
$query = "SELECT * FROM pet where pet_cat = 'D' ORDER BY petid ";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['petname'] = $row['petname'];
$_SESSION['petdesc'] = $row['petdesc'];
$_SESSION['petimg'] = $row['petimg'];
$_SESSION['petid'] = $row['petid'];
echo '<li style="
padding-right: 20px;
padding-left: 20px;">';
echo '<a style= "cursor: pointer;"onclick= "document.getElementById(\'dogmod'.$row['petid'].'\').style.display=\'block\'">';
echo '<img src="data:image/jpeg;base64,'.base64_encode($_SESSION['petimg'] ).'" />';
echo '<h4>';
echo $_SESSION['petname'] ;
echo '</h4>';
include 'desca.php';
echo '</a>';
echo '</li>';
}
And in your modal php file, change only your first line to:
<div id="dogmod<?=$_SESSION['petid']?>" class="modal">
You should be good to go.
To make it close just fine, do the following in your modal php template find the 'close' link:
<span onclick="document.getElementById('dogmod<?= $_SESSION['petid'] ?>').style.display='none'" class="close" title="Close">×</span>
I created a website selling components. Each component has 9 products. How can I add a dropdown button which can arrange the product showing by its Price or Name?
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info"><?php echo $row["p_name"]; ?></h5>
<img src="<?php echo $row["image"]; ?>" class="img-responsive">
<h5 class="text-danger">$ <?php echo $row["price"]; ?></h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="<?php echo $row["p_name"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
<?php
}
}
?>
<?php
}
?>
</div>
</div>
Perhaps you could use Javascript as well and add a few select boxes to give Users the chance to choose the Attribute they want to sort by and also the Direction of the Sorting as in ASC or DESC. The Code Snippet below might shed some light:
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
// CREATE VARIABLES TO HOLD THE SELECT OPTIONS VALUES FOR THE SORTING...
$sortParam1 = 'price';
$sortParam2 = 'name';
$sortDir1 = 'ASC';
$sortDir2 = 'DESC';
// START BUILDING THE OUTPUT...
$output = "<div class='col-md-12'>"; //<== WRAPPER FOR SORING & DIRECTION BOXES
$output .= "<form method='post' action='' id='sorting_form'>"; //<== FORM FOR THE SORTING: SUBMITS TO SAME SCRIPT
// SORTING
$output .= "<div class='col-md-6'>";
$output .= "<select name='sorting' id='sorting'class='form-control'>";
$output .= "<option value='id'>Sorting</option>";
$output .= "<option value='{$sortParam1}'>{$sortParam1}</option>";
$output .= "<option value='{$sortParam2}'>{$sortParam2}</option>";
$output .= "</select>";
$output .= "</div>";
// DIRECTION
$output .= "<div class='col-md-6'>";
$output .= "<select name='direction' id='direction'class='form-control'>";
$output .= "<option value='ASC'>Sort Direction</option>";
$output .= "<option value='{$sortDir1}'>{$sortDir1}</option>";
$output .= "<option value='{$sortDir2}'>{$sortDir2}</option>";
$output .= "</select>";
$output .= "</div>";
$output .= "</form>"; //<== CLOSE SORTING FORM...
$output .= "</div>"; //<== CLOSE WRAPPER...
$rowData = "";
// WE USE JQUERY BELOW TO SUBMIT THE SORTING FORM ONCE USER
// SELECTS ANY OPTION FROM.... SO WE NOW HANDLE THAT SCENARIO HERE USING PHP
if(isset($_POST['sorting']) || isset($_POST['direction']) ){
$sortDirection = isset($_POST['direction']) ? $_POST['direction'] : $sortDir1; // DEFAULTS TO ASC
$sortField = isset($_POST['sorting']) ? $_POST['sorting'] : 'id'; // DEFAULTS TO id
$query = "SELECT * FROM products ORDER BY {$sortField} {$sortDirection}";
$result = mysqli_query($connect, $query);
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)) {
// USE HEREDOC TO CAPTURE THE DATA WITHIN THE LOOP...
$rowData .=<<<R_DATA
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id={$row["id"]}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info">{$row["p_name"]}</h5>
<img src="{$row["image"]}" class="img-responsive">
<h5 class="text-danger">\$ {$row["price"]}</h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="{$row["p_name"]}">
<input type="hidden" name="hidden_price" value={$row["price"]}">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
R_DATA;
} // CLOSE WHILE LOOP
} // CLOSE IF CONDITIONAL LOGIC
// ADD THE DATA GATHERED FROM WHILE LOOP ($rowData) TO THE OUTPUT: $output
$output .= $rowData;
$output .= "</div>\n</div>"; // THESE APPEAR IN YOUR CODE BUT SEEM IRRELEVANT HERE...
// DISPLAY THE OUTPUT
echo $output;
?>
<!-- ENTER JAVASCRIPT: JQUERY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var sortForm = $("#sorting_form");
var sortBox = $("#sorting");
var directionBox = $("#direction");
var bothBoxes = sortBox.add(directionBox);
// IF EITHER OF THE SORTING OR DIRECTION IS CHANGED
// JUST SUBMIT THE FORM
bothBoxes.on("change", function(evt){
sortForm.submit();
});
});
})(jQuery);
</script>