I'm outputting a calendar which will ultimately appear as a series of buttons for the end user. Each button will have the name of the event. When you tap on a button, it will toggle down to show you a short description and the date/time for the event.
So far I've got all the event buttons to show. However, when you click on any button, only the very top event's description and date/time show. What I need help with then is figuring out how to assign each event instance a unique div ID. I tried some other examples on here, but because the following code is written in PHP, just creating a var = blank; throws a processing error.
public function event_block($title, $desc, $start, $end, $where = NULL, $img = NULL, $span = 6)
{
$start_arr = date_parse($start);
$start_stamp = mktime($start_arr['hour'], $start_arr['minute'], $start_arr['second'], $start_arr['month'], $start_arr['day'], $start_arr['year']);
$start_date_int = date('Ymd', $start_stamp);
$end_arr = date_parse($end);
$end_stamp = mktime($end_arr['hour'], $end_arr['minute'], $end_arr['second'], $end_arr['month'], $end_arr['day'], $end_arr['year']);
$end_date_int = date('Ymd', $end_stamp);
$today_date_int = date('Ymd');
$time_range = date('g:i a', $start_stamp) . ' to ' . date('g:i a', $end_stamp);
if ($start_date_int == $today_date_int) {
$date = 'Today';
if ($start_date_int < $end_date_int) {
$time_range = 'Until ' . date('l, F jS', $end_stamp);
}
} else {
$date = date('l, F jS', $start_stamp);
if ($start_date_int < $end_date_int) {
$time_range = 'From' . date('l, F jS', $start_stamp) . ' through ' . date('l, F jS', $end_stamp);
}
}
$output = '
<!-- Event Block -->
<div class="span' . $span . ' event">
<div class="panel-group id="accordion">
<div class="panel-heading">
<a data-toggle="collapse" data-parent="#accordion" href="#addMore" class="btn btn-primary btn-lg">' . $title . '</a>';
if (trim($desc) && $date == 'Today') {
$output .= '<div id="addMore" class="panel-collapse collapse">
<div class="panel-body">' . trim($desc) . '</div>';
}
$output .= '<p style="padding-left: 5px;">';
if (trim($desc) && $date != 'Today') {
$output .= '<div id="addMore" class="panel-collapse collapse">
<div class="panel-body">' .trim($desc) . '</div>';
$output .= '<span style="color: #E8D0A9;">Date:</span> ' . $date . '<br />';
}
$output .= '<span style="color: #E8D0A9;">Time:</span> ' . $time_range . '</p></div>';
return $output;
}
This is the helpful post I looked at before: Create Dynamic div with unique IDs - jQuery
Below is the code on my calendar.php which uses the data from above to generate the calendar of events:
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
require_once('include/event_signage.php');
$sign = new Signage;
// Collect and format all the data
$hero_content = array(
'heading' => '',
'text' => '',
);
$events_now_arr = $sign->databoard_get('URL');
$events_today_arr = $sign->databoard_get('URL');
$events_week_arr = $sign->databoard_get('URL');
// Build the sign
$signage = $sign->header();
//$signage .= $sign->masthead($masthead_content);
$signage .= '<div class="container-fluid"> <!-- container -->';
$signage .= $sign->hero_unit($hero_content);
$event_ids = array();
// Happnening Now
if (count($events_now_arr)) {
$signage .= '<div><h2>Right now!</h2></div>';
foreach ($events_now_arr as $events_arr) {
if (!in_array($events_arr['id'], $event_ids) && $events_arr['cal_id'] != 'community') {
$blocks[] = $sign->event_block($events_arr['title'], $events_arr['description'], $events_arr['start'], $events_arr['end']);
}
$event_ids[] = $events_arr['id'];
}
$signage .= $sign->gather_blocks($blocks);
unset($blocks);
}
// Happening today
if (count($events_today_arr)) {
$signage .= '<div><h2>Today</h2></div>';
foreach ($events_today_arr as $events_arr) {
if (!in_array($events_arr['id'], $event_ids) && $events_arr['cal_id'] != 'community') {
$blocks[] = $sign->event_block($events_arr['title'], $events_arr['description'], $events_arr['start'], $events_arr['end']);
}
$event_ids[] = $events_arr['id'];
}
$signage .= $sign->gather_blocks($blocks);
unset($blocks);
}
// Happening this week
if (count($events_week_arr)) {
$current_hour = date('G');
$cutoff = 39;
if ($current_hour <= 16) {
$cutoff = 27;
if ($current_hour <= 14) { $cutoff = 24; }
if ($current_hour <= 13) { $cutoff = 21; }
if ($current_hour <= 12) { $cutoff = 18; }
if ($current_hour <= 10) { $cutoff = 15; }
}
$signage .= '<div><h2>This Week</h2></div>';
$i = 0;
foreach ($events_week_arr as $events_arr) {
if (!in_array($events_arr['id'], $event_ids) && $events_arr['cal_id'] != 'community' && $i < $cutoff) {
$blocks[] = $sign->event_block($events_arr['title'], $events_arr['description'], $events_arr['start'], $events_arr['end'], NULL, NULL, 4);
$i++;
}
$event_ids[] = $events_arr['id'];
}
$signage .= $sign->gather_blocks($blocks, 3);
unset($blocks);
}
$signage .= '</div> <!-- /container -->';
$signage .= $sign->footer();
// Output the sign
print $signage;
?>
You're going about it wrong. You don't really need to assign a unique id to any of the divs. You just need some standard DOM operations. e.g
<div>
calendar entry #1
<div>more information that's hidden for entry #1</div>
<button onclick="showMore(this);">click here for more</button>
</div>
<div>
calendar entry #2
<div>more information that's hidden for entry #2</div>
<button onclick="showMore(this);">click here for more</button>
</div>
Since every element in the DOM KNOWS where it is in the tree, you don't need a specific ID on that first container div, you just need to know which button got clicked on, which is why this is being passed into the showMore() function:
function showMore(obj) {
obj.previousSibling().style.display = 'block'; // the more info div
}
Of course, this code isn't particularly "portable". it assumes the "more info" div is always going to be right next to the "toggle" button, but this should be enough to give you the general idea.
Related
I'm making a product listings page that uses AJAX calls to post the user's inputted data:
The pagination uses the jQuery inView function to call the next page
(NextPage.php) when loader.gif is in view
InfiniteScroll.js
$(document).ready(function() {
$('#Loader').on('inview', function(event, isInView) {
if (isInView) {
//Pagination
var nextPage = parseInt($('#pageno').val()) + 1;
//Filters
var minimum_wt = $('#hidden_minimum_wt').val();
var maximum_wt = $('#hidden_maximum_wt').val();
var shape = get_filter('shape');
var color = get_filter('color');
var enhancement = get_filter('enhancement');
var matching = get_filter('matching');
$.ajax({
type: 'POST',
url: 'vendors/php/NextPage.php',
data: {
pageno: nextPage,
minimum_wt: minimum_wt,
maximum_wt: maximum_wt,
shape: shape,
color: color,
enhancement: enhancement,
matching: matching
},
cache: false,
success: function(data) {
console.log(nextPage); //For debugging
if(data != '') {
$('#StoneContainer').append(data);
$('#pageno').val(nextPage);
} else {
$('.LoaderContainer').hide(); //Hide infinite scroll
}
}
});
}
});
});
//Checking applied filters
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function() {
filter.push($(this).val());
});
return filter;
}
NextPage.php
<?php
if(isset($_GET['pageno']) || isset($_POST['action'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = $_POST['pageno'];
}
$limit = 10;
$offset = ($pageno-1) * $limit;
//Include database configuration file
include('dbConfig.php');
$SQL = "
SELECT
number,
image1,
wt,
TRUNCATE(length,1) as length,
TRUNCATE(width,1) as width,
CASE
WHEN stonetype = 'SA' THEN 'Sapphire'
WHEN stonetype = 'RU' THEN 'Ruby'
WHEN stonetype = 'TML-P' THEN 'Paraiba'
WHEN stonetype = 'EM' THEN 'Emerald'
WHEN stonetype = 'TS' THEN 'Tsavorite'
WHEN stonetype = 'SI' THEN 'Spinel'
WHEN stonetype = 'GT' THEN 'Garnet'
WHEN stonetype = 'BER' THEN 'Beryl'
WHEN stonetype = 'TML' THEN 'Tourmaline'
WHEN stonetype = 'KO' THEN 'Kornerupine'
ELSE 'n/a'
END AS 'stonetype',
CASE
WHEN enhcode = 'H' THEN 'Heated'
WHEN enhcode = 'N' THEN 'Unheated'
ELSE 'n/a'
END AS 'enhcode'
FROM
stones
WHERE
wt >= 2.5
";
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"])) {
$SQL .= "
AND wt BETWEEN '".$_POST["minimum_wt"]."' AND '".$_POST["maximum_wt"]."'
";
}
if(isset($_POST["shape"])) {
$shape_filter = implode("','", $_POST["shape"]);
$SQL .= "
AND stoneshape IN('".$shape_filter."')
";
}
if(isset($_POST["color"])) {
$color_filter = implode("','", $_POST["color"]);
$SQL .= "
AND stonecolor IN('".$color_filter."')
";
}
if(isset($_POST["enhancement"])) {
$enhancement_filter = implode("','", $_POST["enhancement"]);
$SQL .= "
AND enhcode IN('".$enhancement_filter."')
";
}
if(isset($_POST["matching"])) {
$matching_filter = implode("','", $_POST["matching"]);
$SQL .= "
AND pair IN('".$matching_filter."')
";
}
$SQL .= "
ORDER BY
wt ASC
LIMIT
" . $offset. ",
" . $limit. "
";
$res_data = mysqli_query($db, $SQL);
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"]) && isset($_POST["shape"]) && isset($_POST["color"]) && isset($_POST["enhancement"]) && isset($_POST["matching"])) {
while($row = mysqli_fetch_array($res_data)) {
echo '
<div class="Stone">
<!-- landing page -->
<a href="#ItemPage" class="ItemLink" rel="modal:open" id="' . $row['number']. '">
<!-- image -->
<div class="StoneData StoneIMG"> <img src="../../../' . $row['image1'] . '"> </div>
<!-- weight -->
<div class="StoneData">' . $row['wt'] . 'Ct</div>
<!-- type -->
<div class="StoneData">' . $row['stonetype'] . '</div>
<!-- enhancement -->
<div class="StoneData">' . $row['enhcode'] . '</div>
<!-- dimensions -->
<div class="StoneData">' . $row['length'] . ' x ' . $row['width'] . '</div>
<!-- item number -->
<div class="StoneData"># ' . $row['number'] . '</div>
</a>
</div>
';
}
}
?>
4 different check box fields and a jQuery range slider so the user
can filter out only the data they want
Filters.js
$(document).ready(function() {
filter_data();
function filter_data() {
var action = 'fetch_data';
//Pagination
var nextPage = parseInt($('#pageno').val()) + 0;
//Filters
var minimum_wt = $('#hidden_minimum_wt').val();
var maximum_wt = $('#hidden_maximum_wt').val();
var shape = get_filter('shape');
var color = get_filter('color');
var enhancement = get_filter('enhancement');
var matching = get_filter('matching');
$.ajax( {
url: 'vendors/php/Filters/FilterData.php',
method: 'POST',
data: {
action: action,
pageno: nextPage,
minimum_wt: minimum_wt,
maximum_wt: maximum_wt,
shape: shape,
color: color,
enhancement: enhancement,
matching: matching
},
async: true,
error:
function(jqXHR, strError) {
if(strError == 'timeout') {
// Do something. Try again perhaps?
alert('Seems like there was an error loading the filters request.');
}
},
success:
function(data) {
$('#StoneContainer').html(data);
$('#pageno').val(nextPage);
$('.LoaderContainer').show(); //Show infinite scroll
},
timeout: 3000
});
}
// Where to find values to be filtered
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function() {
filter.push($(this).val());
});
return filter;
}
// Apply filter_data() of .common_selector
$('.common_selector').click(function() {
filter_data();
});
// Range slider
$('#wt_range').slider({
range: true,
values: [2.5, 30],
min: 2.5,
max: 30,
step: 0.1,
slide:
function(event, ui) {
// prevent thumbs from overlapping
if ((ui.values[1] - ui.values[0]) < 3) {
return false;
}
$('#wt_show').html(ui.values[0] + 'Ct - ' + ui.values[1] + 'Ct');
$('#hidden_minimum_wt').val(ui.values[0]);
$('#hidden_maximum_wt').val(ui.values[1]);
filter_data();
}
});
// open and close filters menu on mobile
if ($('#StoneContainer').width() < 420 ) {
$('.OpenCloseFilters').on('click', function() {
$('.FiltersContainer').slideToggle();
// refresh button
$('.ResetFiltersToggle0').toggleClass('ResetFiltersToggle1');
// change icon on toggle
$('#MenuIcon').toggleClass('mdi-menu-up mdi-menu-down');
});
}
});
FilterData.php
<?php
if(isset($_POST['pageno']) || isset($_POST['action'])) {
//Include database configuration file
include('../dbConfig.php');
$limit = 10;
$offset = !empty($_POST['pageno']) ? $_POST['pageno']: 0;
$SQL = "
SELECT
number,
image1,
wt,
TRUNCATE(length,1) as length,
TRUNCATE(width,1) as width,
CASE
WHEN stonetype = 'SA' THEN 'Sapphire'
WHEN stonetype = 'RU' THEN 'Ruby'
WHEN stonetype = 'TML-P' THEN 'Paraiba'
WHEN stonetype = 'EM' THEN 'Emerald'
WHEN stonetype = 'TS' THEN 'Tsavorite'
WHEN stonetype = 'SI' THEN 'Spinel'
WHEN stonetype = 'GT' THEN 'Garnet'
WHEN stonetype = 'BER' THEN 'Beryl'
WHEN stonetype = 'TML' THEN 'Tourmaline'
WHEN stonetype = 'KO' THEN 'Kornerupine'
ELSE 'n/a'
END AS 'stonetype',
CASE
WHEN enhcode = 'H' THEN 'Heated'
WHEN enhcode = 'N' THEN 'Unheated'
ELSE 'n/a'
END AS 'enhcode'
FROM
stones
WHERE
wt >= 2.5
";
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"])) {
$SQL .= "
AND wt BETWEEN '".$_POST["minimum_wt"]."' AND '".$_POST["maximum_wt"]."'
";
}
if(isset($_POST["shape"])) {
$shape_filter = implode("','", $_POST["shape"]);
$SQL .= "
AND stoneshape IN('".$shape_filter."')
";
}
if(isset($_POST["color"])) {
$color_filter = implode("','", $_POST["color"]);
$SQL .= "
AND stonecolor IN('".$color_filter."')
";
}
if(isset($_POST["enhancement"])) {
$enhancement_filter = implode("','", $_POST["enhancement"]);
$SQL .= "
AND enhcode IN('".$enhancement_filter."')
";
}
if(isset($_POST["matching"])) {
$matching_filter = implode("','", $_POST["matching"]);
$SQL .= "
AND pair IN('".$matching_filter."')
";
}
$SQL .= "
ORDER BY wt ASC
LIMIT
$offset,
$limit
";
$result = mysqli_query($db, $SQL);
$output = '';
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"]) && isset($_POST["shape"]) && isset($_POST["color"]) && isset($_POST["enhancement"]) && isset($_POST["matching"])) {
if($row = mysqli_fetch_array($result)) {
foreach($result as $row) {
$output .= '
<div class="Stone">
<!-- landing page -->
<a href="#ItemPage" class="ItemLink" rel="modal:open" id="' . $row['number']. '">
<!-- image -->
<div class="StoneData StoneIMG"> <img src="../../../' . $row['image1'] . '"> </div>
<!-- weight -->
<div class="StoneData">' . $row['wt'] . 'Ct</div>
<!-- type -->
<div class="StoneData">' . $row['stonetype'] . '</div>
<!-- enhancement -->
<div class="StoneData">' . $row['enhcode'] . '</div>
<!-- dimensions -->
<div class="StoneData">' . $row['length'] . ' x ' . $row['width'] . '</div>
<!-- item number -->
<div class="StoneData"># ' . $row['number'] . '</div>
</a>
</div>
';
}
}
} else {
$output = '
<h1 class="Error">
<span class="mdi mdi-filter-remove mdi-48px"></span>
NO STONES MATCH THAT
</h1>
';
}
echo $output;
}
?>
My problem is when the user updates the filters my pagination jumps to the next page so not only will they not see the else statement on FilterData.php (which can obviously be very confusing for the user) but they will get a totally blank page, even when there are some results.
I imagine the solution to be resetting to the first page (of my pagination) every time the data updates. But for some reason I can't figure out how to do it. I tried changing line 52 of Filters.js to $('#pageno').val(0);, but that didn't seem to work as expected.
I know this is probably a very simple issue for you guys and i'm sort of embarrassed even asking but I've been trying to fix this since last Wednesday and still can't get it (i'm pretty new to php). Thank you so much for your time in advance!
I have a project where I filter the elements by clicking on the checkbox. I think biggest problem is with jQuery.each() function. You can see code below what it does. I need to create only one array and filter values only in this array, because now, i am getting duplicates. Is there any way how to fix this with jQuery.each() or i need to use another function? I know how this problem arises, but I didn't find a solution.
Of course, data for every checkbox are mixed. For example, some data fall under all checkboxes, another data only to one checkbox etc. You can see get_filter function.
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var brand = get_filter('brand');
var jackpot = get_filter('jackpot');
var volatility = get_filter('volatility');
var special_features = get_filter('special_features');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, brand:brand, jackpot:jackpot, volatility:volatility, special_features:special_features},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
console.log(filter);
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
fetch_data.php
<?php
//fetch_data.php
include 'template.php';
$pdo = pdo_connect_mysql();
if(isset($_POST["action"]))
{
$query = ('SELECT * FROM slotselect.slot WHERE 1');
$query2 = ('SELECT * FROM slotselect.slot, slotselect.slot_features, slotselect.special_features WHERE slot_features.id_slot = slot.id_slot AND slot_features.id_sf = special_features.id_sf');
if(isset($_POST["special_features"]))
{
$sf_filter = implode("','", $_POST["special_features"]);
$query .= " AND special_features.id_sf IN('".$sf_filter."') ";
$query2 .= " AND special_features.id_sf IN('".$sf_filter."') ";
}
if(isset($_POST["brand"]))
{
$brand_filter = implode("','", $_POST["brand"]);
$query .= " AND id_provider IN('".$brand_filter."') ";
$query2 .= " AND id_provider IN('".$brand_filter."') ";
}
if(isset($_POST["jackpot"]))
{
$jackpot_filter = implode("','", $_POST["jackpot"]);
$query .= " AND id_jackpot IN('".$jackpot_filter."') ";
$query2 .= " AND id_jackpot IN('".$jackpot_filter."') ";
}
if(isset($_POST["volatility"]))
{
$volatility_filter = implode("','", $_POST["volatility"]);
$query .= " AND id_vol IN('".$volatility_filter."') ";
$query2 .= " AND id_vol IN('".$volatility_filter."') ";
}
$statement = $pdo->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if(isset($_POST["special_features"]))
{
$statement = $pdo->prepare($query2);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'.$namee['name'].'</h4>
<p></p>
View
<p></p>
</div>
</div>';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'. $namee['name']. '</h4>
<p></p>
View
<p></p>
</div>
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
Some examples:
https://imgur.com/UbeZv72
https://imgur.com/DzMvIMe
https://imgur.com/NTIMbtg
If you just want to transmit one Array with all the ID's to your fetch_data.php you coud rewrite your js-code like this:
var filter_array = [
'brand',
'jackpot',
'volatility',
'special_features'
];
filter_data(filter_array);
function filter_data(filter_array)
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var selected_filters = get_filter(filter_array);
console.log(selected_filters);
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, filters:selected_filters}, //selected_filters Structure = [brand:'brand_value',jackpot:'jackpot_value', ... ]
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(filter_array, filter = []){
if (filter_array === undefined || filter_array.length == 0) { //check if array exists or if there are filters left to add
var class_name = filter_array.shift(); //Removes and returns first element of filter_array
$('.'+class_name+':checked').each(function(){
filter[class_name] = $(this).val();
get_filter(filter_array,filter); //called recursivly as long as there are filters to add
});
}
else{
return filter;
}
}
$('.common_selector').click(function(){
filter_data();
});
This might not use jquery.each() but it will produce an array with all the checked boxes names and values which you can iterate in you php by using foreach like this:
foreach($_POST['filters'] as $key => $value){
//$key = the name of the checkbox selector | $value = the value of the associated checkbox
}
This code is NOT TESTET, but i still hope it helps.
I have an input[type="file"] had multiple option. I made it preview function so that user can delete the image by clicking the button before submit. The images are deleted well on browser by remove() function however the problem is the values of input including the deleted images are posted when i submit. I don't know how to delete real value of input.
I've tried to figure it out to delete in the server side.
This is the part of html code.
<div class="col-xs-4 vcenter from-group">
<span class="glyphicon glyphicon-asterisk" style="color:red;"></span><label for="inputScreenshots">스크린샷</label>
<p style="display:inline; padding-left:270px; color:red; font-size: 12px">* 이미지 사이즈 : 800 X 450</p>
<input type="file" id="inputScreenshots" name="inputScreenshots[]" class="form-control" accept="image/*" multiple>
<div id="filenameList" style="width : 400px">
<div id="insertScreenshots" style="margin : 30px; position :relative;">
<input type="hidden" name="screenshots_filename[]" value="<?=$screenshot_urls?>">
</div>
</div>
This is the php code where im trying to defend uploading images.
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
// del_screenshots are images that deleted from client.
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
// ss_count is the size of all images including deleted images from input field.
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
// tmp_filename is the posted real file name.
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
//=========================================================================
for ($j = 0; $j < sizeof($ds_count); $j++) {
// Compare all images name and deleted images name
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
// The $tmp_filename has to be deleted. not to be uploaded to server.
// $tmp_filename = null;
}else {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."false";
// This files are okay to be uploaded to server.
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
$newFilePath = uniqid().".".$ext;
if ($screenshots != "") {
$screenshots .= "+";
}
$screenshots .= $newFilePath;
// $screenshots has be uploaded to DB except the deleted images. (ex : uniqFileName.png + uniqFileName.png + .. )
echo "<br/> 1) screenshots : ". $screenshots;
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
$ss_upload="true";
}
I want to defend uploading the deleted images but it is no matter to use unlink() in somewhere. The point is how cant i make the string except the deleted images.
=========================================================================
I suppose there is another way to do in jQuery but i have no idea.
I'll put the code below.
$("#inputScreenshots").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = screenshots_processFile(file);
fr.readAsDataURL(file);
}
});
var screenshots_processFile = function screenshots_processFile(file) {
return (function(file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin: "30px",
position: "relative"
});
var html = [,'<img src="" width="100%" id="tmp_screenshots">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function() {
alert("remove");
//=========================================================== * TODO : remove the files in server!
var targetDom = document.getElementById( "filenameList" );
var targetInput = document.createElement("input");
targetInput.setAttribute("name", "del_screenshots[]" );
targetInput.setAttribute("type","hidden");
targetDom.appendChild(targetInput);
alert(file.name);
targetInput.setAttribute("value", file.name);
//===========================================================
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file)
};
How can i do this? Does anyone have an idea?
-----------------------------------------------------------------------------------------------------------
I solved it like this. I know my code is so dirty :-/
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
//echo "<br/> << TEST >>"."<br/>ds_count[0] : " . $ds_count[0] . "<br/>ds_count[1] : " . $ds_count[1] ;
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
$ss_del_mode="false";
//=========================================================================
if (isset($_POST["del_screenshots"])) {
for ($j = 0; $j < sizeof($ds_count); $j++) {
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
$ss_del_mode = "true";
}
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
if ($ss_del_mode == "true") {
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
$newFilePath = "";
} else {
$newFilePath = uniqid().".".$ext;
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
}
if ($screenshots != "") {
if ($ss_del_mode != "true"){
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]". " --> screenshots";
$screenshots .= "+";
}
}
$screenshots .= $newFilePath;
echo "<br/> 1) screenshots (newFilePath) : ". $screenshots;
if ($newFilePath != "") {
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
}
$ss_upload="true";
}
I have a minor problem.
Left side navigation menu toggle <--- website link - see left category navigation.
As you see in the link above, this is a left side navigation with toggle option. When clicking on the + sign the submenu gets unfolded and the + sign becomes a - sign, when clicking the - sign it gets back to normal.
The title on the left side is a link, when clicking on the title on the left it gets be directly ex. to the Fast Food category. However, I would like the title to have the same option as the +/- sign - and removing the link class.
The HTML code is:
<div class="block block-side-nav-container">
<div class="block-title">
<strong><span><?php echo $this->__('Categories') ?></span></strong>
</div>
<div class="block-content">
<div class="side-nav">
<ul id="category-treeview" class="treeview-side treeview">
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php echo $this->drawItem($_category) ?>
<?php endforeach ?>
</ul>
</div>
</div>
I might think that the code is a php language, please see below:
protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
$isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
{
if (!$category->getIsActive()) {
return '';
}
$html = array();
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array)$category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = ($children && $childrenCount);
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="'.$outermostItemClass.'"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$htmlLi = '<li';
foreach ($attributes as $attrName => $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . '"';
}
$htmlLi .= '>';
$html[] = $htmlLi;
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
($j == $activeChildrenCount - 1),
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
}
Please help.
Thank you!
You could fix this with jQuery.
All you have to do is add a slideToggle function to your menutitle.
First be sure to include jQuery in your site
Create a js file for little js fixes (i usually call it customjs.js) and include from the footer of your site
Add the following jQuery
$(".block-title").click(function(){
$(".block-content").slideToggle(); //SLIDE TOGGLE FOR SLIDING UP AND DOWN
return false; // PREVENTS LINK FROM WORKING
})
Check jsfiddle.net/pTg68/17/ for an example
Cheerz
Firstly find what the function is called, I would imagine it look something like this:
var menu = "closed";
function toggleMenu(){
if(menu = "closed"){
openTree();
}else{
closeTree();
}
}
function openTree(){
//code to open the menu
};
function closeTree(){
//code to close the menu
};
And all you would do is change the link from each category from
Fast Food
to
Fast Food
Ok so all of the other functions I've done this same way have worked so far. This one for whatever reason will not work.I don't know if there is something I"m missing or if maybe a potential error in the code earlier could cause this. Here is my code:
jQuery("#teamTab_addPlayerForm").on('change', 'select#teamTab_suggestedPlayer', function(e) {
e.preventDefault();
alert('It Worked');
});
And here is the PHP file that calls it:
$output .= '<div id="ld_addPlayerFunction" style="clear:both; width:100%;"><h3>Add Player</h3>';
$standins = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'kdc_user_sync ORDER BY computedMMR ASC');
$output .= '<form id="teamTab_addPlayerForm" action="" method="POST">
<select id="teamTab_suggestedPlayer" name="suggestedPlayer">
<option value="base">Suggested Player</option>';
foreach($standins as $standin){
$playerID = $wpdb->get_var('SELECT ID FROM ' . $wpdb->prefix . 'leagueDesigner_players WHERE userID = ' . $standin->userID);
$test = true;
if($playerID != ''){
$leagueTest = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_league_players WHERE playerID = ' . $playerID);
foreach($leagueTest as $test){
if ($test->leagueID == $leagueID){
$test = false;
}
}
}
if($standin->computedMMR < ($suggestedMMR + 100) && $standin->computedMMR > ($suggestedMMR -100) && $test == true){
$output .= '<option value="' . $standin->userID . '">' . substr($standin->profileName, 0, 20) . ' - ' . $standin->computedMMR . ' MMR</option>';
}
}
$output .= '</select><br />';
$output .= '</form>';
The output is then echoed later in the script. So one user has told me to use document instead of #teamTab_addPlayerForm and it works, but I'm wondering why this previous code worked fine and that one didn't:
jQuery("#teamTab_teamListForm").on('change', 'select#teamTab_teamSelect', function (e) {
e.preventDefault();
jQuery(this).attr('disabled', true);
var teamID = jQuery(this).val();
jQuery('select#teamTab_leagueSelect').attr('disabled', true);
var leagueID = jQuery('select#teamTab_leagueSelect').val();
data = { action: "leagueDesignerTeamsTabLoadTeamPlayers", leagueID: leagueID, teamID: teamID };
jQuery.ajax({
type: 'POST', url: ajaxurl, data: data, dataType: 'html', success: function(response) {
if (response == "error") {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
alert('There was an error processing your request');
}
else {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
jQuery('select#teamTab_leagueSelect').attr('disabled', false);
jQuery('.ld_teamEdit').remove();
jQuery('#ld_addPlayerFunction').remove();
jQuery('div#ld_teamTabTeamInfo').remove();
jQuery('#teamTab_teamListForm').after(response);
}
}});
});
That was the code that is dealing with select boxes in the same way. And here is the PHP code:
function leagueDesignerTeamsTabLoadLeagueTeams () {
global $wpdb;
$leagueID = $_POST['leagueID']; //Pull the POST'd leagueID
$output = '<select id="teamTab_teamSelect" name="team"><option value="">Choose a Team</option>'; //Output...
$errors = 0; //Error checking...
$teams = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_teams WHERE leagueID = ' . $leagueID);
foreach($teams as $team){
$output .= '<option value="' . $team->teamID . '"';
if ($_POST['team'] == $team->teamID){
$output .= ' selected';
}
$output .= '>' . $team->teamID . '. ' . $team->teamName . '</option>';
}
if (!$teams) {
$errors++;
}
$output .= '</select>';
if ($errors == 0) { echo $output; } else { echo 'error'; }
die(); // this is required to return a proper result
}
The element is created after page load so you need to bind it to an already existing element (see below)
$(document).on('change', '.class-name', function () {
//Commands to run on change
});