How to use javascript if statement correct? - javascript

So I have this program that whenever the expiration date is exactly the same date as today the background of the <div> will change it color. But right now, the background color change only when my condition is == and when I try to use>= or <= the background color does not change. Also the background color change even the expiration date is not the same as the date today
Here is my javascript:
<script type="text/javascript">
var $today = date("m/d/Y");
var $expired = $passport_expiration;
function myDIV() {
if ($today == $expired) {
document.getElementById("myDiv").style.backgroundColor="#ff4d4d";
}
}
</script>
Here's my HTML:
<div class="col-md-6" id="myDiv">
<div class="alert" role="alert"><span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <?php echo "<strong> $passport / Passport Expiration Date:</strong> $passport_expiration"; ?></div>
</div>
How I get the $today and passport_expiration, it is in my query
Thank you in advance

<div class="col-md-6" id="myDiv">
<div class="alert" role="alert">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span>
Passport <?php echo "<strong> $passport /
Passport Expiration Date:</strong> $passport_expiration"; ?></div>
<input type="hidden" id="passport_expire_date" name="passport_expire_date" value="<?php echo $passport_expiration; ?>">
<?php $date = date("m/d/Y "); ?>
<input type="hidden" id="today_date" name="today_date" value="<?php echo $date; ?>">
</div>
u need to assign that values in input field then only, it will be validated in javascript
<script type="text/javascript">
var today = document.getElementById("today_date");
var expired = document.getElementById("passport_expire_date");
function myDIV() {
if ($today == $expired) {
document.getElementById("myDiv").style.backgroundColor="#ff4d4d";
}
}
</script>

Related

How to disabled picked date in daterangepicker connected to database

How to disable date already picked before in PHP 5 and database using MYSQL, and I tried several time but nothing to work, and I tried to make a booking system
<div class="row">
<div class="col-xs-3">
<label class="form-control" style="border:none;">Publish Date</label>
</div>
<div class="col-xs-3">
<input type="text" name="txtPublishDate" id="txtPublishDate" class="form-control" value="<?php echo $PublishDate; ?>" placeholder="Publish Date" />
</div>
</div>
<script>
$(function() {
$('input[name="txtPublishDate"]').daterangepicker({
opens: 'right'
}, function(start, end, label) {
console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
});
});
<input .... <?php echo is_string($PublishDate) ? ' disabled="disabled" readonly' : ''; ?> />
Or, don't even put the input based on if you've already picked it. Show the chosen value in a tag like a span instead. Then the JS won't bind to the disabled input.
eg:
<?php if !is_string($PublishDate) { ?>
<input .... />
<?php } else { ?>
<span><?php echo $PublishDate ?></span>
<?php } ?>

Unset a single item form a php array embedded in a html site with JS button

My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});
PHP and HTML:
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
print("<div class=\"basket-product\">
<div class=\"item\">
<div class=\"product-image\">
<img src=\"http://placehold.it/120x166\" alt=\"Placholder Image 2\" class=\"product-frame\">
</div>
<div class=\"product-details\">
<h1><strong><span class=\"item-quantity\">1</span> x ".$data["StockItemName"]."</strong></h1>
<p><strong>".$color." ".$size."</strong></p>
<p>Product Code - ".$data["StockItemID"]."</p>
</div>
</div>
<div class=\"price\">".$data["RecommendedRetailPrice"]."</div>
<div class=\"quantity\">
<input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">
</div>
<div class=\"subtotal\">". $data["RecommendedRetailPrice"] * 1 ."</div>
<div class=\"remove\">
<button>Remove</button>
</div>
</div>");
}
I tried using Unset in allot of places, but that doesn't seem to get working :')
:)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:
Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);
Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the <div class="basket-product"> and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).
Create a callback function for removal on('click', function(){});
Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');
Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4
On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
?>
<div class="basket-product">
<div class="item">
<div class="product-image">
<img src="http://placehold.it/120x166" alt="Placholder Image 2" class="product-frame">
</div>
<div class="product-details">
<h1>
<strong>
<span class="item-quantity">
1
</span>
x <?php echo $data["StockItemName"]; ?>
</strong>
</h1>
<p>
<strong>
<?php echo $color." ".$size; ?>
</strong>
</p>
<p>
Product Code - <?php echo $data["StockItemID"]; ?>
</p>
</div>
</div>
<div class="price">
<?php echo $data["RecommendedRetailPrice"]; ?>
</div>
<div class="quantity">
<input type="number" value="1" min="1" class="quantity-field">
</div>
<div class="subtotal">
<?php echo $data["RecommendedRetailPrice"]; ?> * 1
</div>
<div class="remove">
<button data-product-id="<?php echo $data["StockItemID"]; ?>">
Remove
</button>
</div>
</div>
<?php
}
?>
JS
$(document).ready(function(){
$('.remove button').on('click', function() {
var stock_item_id=$(this).attr('data-product-id');
$.ajax({
url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
data:
{stock_item_id : stock_item_id}
}).done(function() {
$("#remove_"+stock_item_id).remove();
});
});
});
NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
$stock_item_id = $_POST['stock_item_id'];
$key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
unset($_SESSION["cart"][$key_to_remove]);
if(isset($_SESSION["cart"][$key_to_remove])) {
return false;
}
return true;
For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)

How to add class dynamically using javascript

I want to add an class to an closest element of an click object.
If you see code below, I would like to add an class to .process-signs-direction-cover-button
There is an loop, so the above classes get's repeated. But I want to add an classes to closest() .process-signs-direction-cover-button of where I click.
See picture
MY php:
<div class="col-md-6 reduced_padding_col7">
<?php
$signs_to_direction_and_cover_process = $mysqli_scs->query("SELECT * FROM agsigns_db3.stock_stk where idstc_stk = ".$row['idstc_stk']." AND directioncolor_stk = 'Yellow' ");
$row_cnt = $signs_to_direction_and_cover_process->num_rows;
if($row_cnt > 0){
while ($row = mysqli_fetch_assoc($signs_to_direction_and_cover_process)) { ?>
<div class="col-md-4 thumbnail"><img src="../../css/sign-directions/<?php echo $row['directionimage_stk']; ?>" class="processing-signs-direction-cover-sign-direction-selection-process" id="<?php echo $row['id_stk']; ?>" />
<div class="col-xs-12 text-center signs-text">
<span class="current_stock_figure">
<?php echo $row['stock_stk'] == "" ? "N/A" : $row['stock_stk']; ?>
</span>
<span class="max_stock_figure">
<?php echo $row['maxlevel_stk']; ?>
</span>
</div>
</div>
<?php
}
}
?>
</div>
<div class="col-md-2 process-button">
<img src="../../css/buttons/process-signs-covered-disabled.png" id="" class="process-signs-direction-cover-button disabled_button" rel="<?php echo $row['signcode_sgn']; ?>" alt="covered"/>
<div class="options-remember-checkbox">
<input type="checkbox" class="rememberoptions" name="rememberoption" value="checked" > Remember Options<br>
</div>
MY JQuery
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").toggleClass("process");
});
Modify
Question Modified
Image code
In your jquery part use addClass instead of toggleClass .
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").addClass("process");
});

Javascript Uncaught SyntaxError: Unexpected token

I am having issues calling my javascript function which loops through an array calling an external PHP page for each value. I get the following error in my developer console in Chrome:
Uncaught SyntaxError: Unexpected token . CSV.php?reg=1:3
When inspecting my values passing to the script everything is there as it should be:
<script type="text/javascript">
function.csvgen(){
var area = "["22","23","24"]";
var start =""2017-01-30"";
var end = ""2017-02-06"";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
I'm not exactly a good programmer and have used very little Javascript (which required assistance from this wonderful forum as well...). Here is my code for the page. The point of the code is to let the user select a number of areas based on their region as well as a start date and an end date and then generate a CSV from my MS SQL database for each, the code for which is in the called CSVGEN.PHP file. I've tested the CSVGen file with a manually generated link and it works, it does not if I put the static link inside the for loop.
<script type="text/javascript">
function.csvgen(){
var area = "<?php echo json_encode(array_values($_POST['arealist'])); ?>";
var start ="<?php echo json_encode($_POST['start']); ?>";
var end = "<?php echo json_encode($_POST['end']); ?>";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
<?php
$page_title="CSV Generator";
include("\Include\header.inc");
include("\Include\connect-db.php");
include("\Include\CSVGen.php");
$error="";
$start_date=date("Y-m-d");
$end_date=date("Y-m-d", strtotime("+7 days"));
if(isset($_GET['reg']))
{
$reg=$_GET['reg'];
}
else{
$reg='1';
}
if($start_date>$end_date){
$error = 'ERROR: End Date cannot be before Start Date!';
}
if ($error != '')
{
echo '<div class="container">
<div class="row">
<div class="alert alert-danger col-md-12">'.$error.'
</div>
</div>
</div>';
}
$sqlareas="SELECT Area_Name, Region_ID, Area_ID FROM Listings_Areas WHERE region = '$reg'";
$arearesult= sqlsrv_query($conn, $sqlareas, array(), array("Scrollable"=>"buffered"));
$areacount = sqlsrv_num_rows($arearesult);
function renderForm($arearesult, $areacount, $start_date, $end_date){
?>
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<form id="CSV" name="form1" method="post">
<div class="col-md-2 col-md-offset-1">
<p><select name="arealist[]" size="<?php echo $areacount ;?>" multiple="multiple" tabindex="1">
<?php
while($areas=sqlsrv_fetch_array($arearesult)){
echo'<option value="' . $areas['Area_ID'] . '">' . $areas['Area_Name'] . '</option>';
}
?>
</select>
</div>
<div class="col-md-3">
<strong>Start Date: </strong> <input type="date" name="start" value="<?php echo $start_date; ?>" />
</div>
<div class="col-md-3">
<strong> End Date: </strong> <input type="date" name="end" value="<?php echo $end_date; ?>" />
</div>
<div class="col-md-2">
<input type="submit" onclick="csvgen()" name="submit" value="Get CSVs">
</div>
</form>
</div>
</div>
<?php
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r(array_values($_POST['arealist']));
echo $_POST['start'];
echo $_POST['end'];
}
else{
renderForm($arearesult, $areacount, $start_date, $end_date);
}
?>
I've tried removing all tabbing/spacing and clearing any potential illegal characters that might have snuck in, but it's showing a period, which I can only guess is referring to either my area.length which as far as I can tell from the manual is right and I still get the error if I remove it or $.getscript, but I've used that elsewhere in similar functions with no issue so I don't know why that would be wrong, or how to replace it.
At the very begining of the script you have:
<script type="text/javascript">
function.csvgen(){
//...
which should be:
<script type="text/javascript">
function csvgen(){
//...
with a space instead . between function and csvgen.
NOTE: this area = "["22","23","24"]"; is also wrong. Use diferent quotes (like area = '["22","23","24"]';) or escape the inner quotes (like area = "[\"22\",\"23\",\"24\"]";)
Find a good javascript tutorial and learn more about how to declare function in javascript.

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

Categories

Resources