I have the following jQuery code below:
My Html:
<div class="input-group top_buffer_small">
<label class="col-md-3 col-sm-3 text_right top_buffer_mini">Available Colors:</label>
<div class="col-md-9 col-sm-9 text_right">
<table id="availColors" align="center">
<?php
//instantiate color class
$colors = $Item->getColors();
$colorCount = $Item->getColorCount();
if($colorCount > 0){
//create a mod since we only want to show 4 colors per row.
$remainder = $colorCount%4;
$x=0; //counter variable
if(is_array($colors)){
foreach ($colors as $key=>$value){
foreach ($value as $color) {
if($remainder == 0){
//if we are at 0, make a new row
echo "<tr>";
}
//print_r($Item->getProductVariations($color));
?>
<td style="background-color:#<?php echo $color;?>" data-pictures="<?php echo htmlspecialchars(json_encode($Item->getProductVariations($color))); ?>" data-directory="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/';?>"></td>
<?php
if($remainder == 3){
//end the row
echo "</tr>";
}
//$x++;
}
}
}
}
?>
</table>
</div>
</div>
Basically, I am trying to get the array values which are being passed from the to my javascript. After I get the values, I am trying to make all the image thumbnails change to the pictures on click of a color.
This is the div I am aiming to change the picture thumbnails:
<div class="row">
<div class="featured_container_small" id="productThumbnails">
<h5>Other Views</h5>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<!-- <div class="col-md-3 buffer_bottom"><img src="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/'.$smallimage1?>" class=" center_image responsive_image"></div> -->
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
</div>
<div class="row">
<div class="col-md-12"><nbsp></nbsp></div>
</div>
<div class="clear"></div>
</div>
Then this is my jquery:
$(function(){
$("#availColors td").click(function(){
var imageDirectory = $(this).attr('data-directory');
var pictures = $(this).attr('data-pictures');
var pictureArray = JSON.parse(pictures);
var productThumbnails = $("#productThumbnails img");
var thumbnailCount = productThumbnails.length;
var keys = Object.keys(pictureArray);
var pic = "";
var src="";
for (var i = 0; i < keys.length; i++) {
pic = pictureArray[keys[i]];
productThumbnails[i].attr("src",imageDirectory+pic+".jpg");
}
});
});
When I perform my click function, an error returns saying "undefined is not a function".
I don't know why its doing this. Some help please.
When you iterate over the images collection, productThumbnails[i] returns the underlying HTMLImageElement which doesn't provide the attr() method. Try to wrap it with jQuery instead:
$(productThumbnails[i]).attr("src",imageDirectory+pic+".jpg");
Also, when using jQuery, the best way to access arbitrary data associated with your DOM elements is using the data() method:
var imageDirectory = $(this).data('directory');
var pictures = $(this).data('pictures');
As a bonus, you'll also get JSON deserialization out of the box and there's no need for JSON.parse():
var pictureArray = $(this).data('pictures');
Related
i am showing travel packages from database in loop on a page, where more than 40-50 packages getting shown.
i want only four packages to be shown at start and when i click on show more button it should show 4 more packages and so on.
<?php foreach($blogrand as $blogsrand){ ?>
<div class="grid-item-wrap large-4 medium-4 small-12 columns group-0">
<div class="shadow grid-item rel bdg1">
<div class="img"><a href="<?=base_url();?>tours/<?php echo $blogsrand['tourslug'];?>"><img alt="<?php echo $blogsrand['tourname'];?>" class="mmtTI hide" src="<?php echo $blogsrand['banner'];?>" /><img alt="<?php echo $blogsrand['tourname'];?>" class="mmtTIM" src="<?php echo $blogsrand['banner'];?>" />
</a></div>
<div class="content eq-7" style="height:110px">
<h3><?php echo $blogsrand['tourname'];?></h3>
<div style="background-color: transparent;width:100%;display: inline-block;padding-top: 1px;padding-bottom: 1px;font-size: 12px; color:#ff9016;" class="bld lsp upc drk" data-popup="range-reveal-1">Trip Type : <?php echo $blogsrand['tourtype'];?><br><span style="text-transform:capitalize; color:black;">Trip Duration : <?php echo $blogsrand['hotels'];?></span><br><span style="text-transform:capitalize; color:#959595;">Places Covered : <?php echo $blogsrand['tourplaces'];?></span></div>
</div>
</div>
</div>
<?php } ?>
<div class="cnt"><a class="bld f19 wht wrBCol3 colLinkPad viewMoreTrigger5">Show More</a></div>
how to achieve this by CSS or Javascript.
Here's a snippet to get you started. Try it out, play around with it, try to adopt it to your use case, and when you encounter specific issues you're unable to debug and figure out yourself, then feel free to ask on stackoverflow. Be sure to include minimum reproducing examples when applicable.
let data = [...Array(50)].map((_, i) => ({i, r: Math.random()}));
document.querySelector('#more-button').addEventListener('click', () => {
let showing = document.querySelector('#container').childElementCount;
for (let i = 0; i < 4; i++) {
let row = document.createElement('div');
let d = data[showing + i];
row.textContent = `${d.i}, ${d.r}`;
document.querySelector('#container').appendChild(row);
}
});
<div id="container"></div>
<button id="more-button">more</button>
I have some list from db using foreach, and now i would like to when i press button print to print all elements with "print" id, but in my case when i click print i only can print first item in list, not all.
<?php $unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2" id="print">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo
$unos[$data]['id'] ?>&print=true" />
</div> </div> <?php }
} ?>
<button onclick="printaj()">Print all</button>
And my JS:
<script>
function printaj() {
var prtContent = document.getElementById("print");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
</script>
id's in HTML must be unique - you create multiple id=print and document.getElementById will return a single element
If it returned multiple elements, your code would still fail, since your code relies on the fact that document.getElementById returns a single element!
So, I'd suggest a single outer div with id=print as follows
<?php
$unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
?>
<div id="print">
<?php
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo $unos[$data]['id'] ?>&print=true" />
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
<button onclick="printaj()">Print all</button>
With this solution, printaj does not need to be changed
Solution 1: use class name instead of ID and itterate through class objects:
function printaj() {
var prtContent ;
var content= document.getElementsByClassName("print");
for(var i = 0; i < content.length; i++)
{
prtContent =prtContent +content(i).innerHTML;
}
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
solution 2:
wrap all generated content inside a single div with id="print" and print it!
I am trying to create a function that when you click up it appends to the div what you want and if you press up again will show what you want again and replace the other data, same for when you press down.
The idea is to have 5 options, the option that it starts on is decided on that users info. So say they are number 3 it will start on number 3 and if you press up it will go to number 2 if you press down it will go to number 4 and show the data with those numbers.
What I am trying to figure out is how can I make this option and then when clicked do what I want it to do.
Idea of what it looks like:
When you press the blue up will go up a page and only show the player that are in diamond 2. and same for the rest
<main>
<div class="panel">
<div class="panel-body"></div>
<div class="league-banner" style="height: 50px;">
<div class="league-number" style="top: 15px; position: relative;">
<div class="league-rank">
III
</div>
<div class="league-buttons">
<img src="img/league/up.png"/>
<a class="sq-btn" href="" style="position: relative; top: -30px;"><img src="img/league/down.png"/></i></a>
</div>
</div>
<span style="color:#57a2dd; font-size: 20px;">DIAMOND 5 </span>
<span style="font-size: 20px;" class="second-banner">Diamond V</span>
<div class="light" style="font-size:20px;">Lee Sin's Redeemers</div>
</div>
<div class="league-top">
<div class="stats-header stats-row">
<div class="table-cell">Rank</div>
<div class="table-cell">Summoner</div>
<div class="table-cell">Emblems</div>
<div class="table-cell">Wins</div>
<div class="table-cell">Losses</div>
<div class="table-cell">Win Rate</div>
<div class="table-cell">Points</div>
</div>
<div class="scroll-league" id="scroll-league">
<?php
if ($league_list){
$entrieszlist = $league_list->entries;
usort($entrieszlist, function($acl,$bcl){
return $bcl->leaguePoints-$acl->leaguePoints;
});
$index = 0;
foreach ($entrieszlist as $datazlistleague){
$playerleagueId = $datazlistleague->playerOrTeamId;
$playerleagueNameSummoner = $datazlistleague->playerOrTeamName;
$playerleagueNameSummonerDivison = $datazlistleague->division;
$playerleagueNameSummonerWins = $datazlistleague->wins;
$playerleagueNameSummonerLosses = $datazlistleague->losses;
$playerleagueNameSummonerLP = $datazlistleague->leaguePoints;
$playerleagueNameSummonerGamesPlayed = $playerleagueNameSummonerWins + $playerleagueNameSummonerLosses;
$playerleagueNameSummonerGamesWinRate = (100/$playerleagueNameSummonerGamesPlayed)*$playerleagueNameSummonerWins ;
$playerleagueNameSummonerLPtarget = $datazlistleague->miniSeries->target;
$playerleagueNameSummonerLPWins = $datazlistleague->miniSeries->wins;
$playerleagueNameSummonerLPLosses = $datazlistleague->miniSeries->losses;
$playerleagueNameSummonerLPProgress = $datazlistleague->miniSeries->progress;
if (isset($datazlistleague->miniSeries)){
$miniSeriesdatayesnodata = 1;
} else {
$miniSeriesdatayesnodata = 2;
}
$summonerData1;
if(isset($playerleagueNameSummoner)) {
$formatedUserName1 = str_replace(" ", "", $playerleagueNameSummoner);
$formatedUserName1 = mb_strtolower($formatedUserName1, 'UTF-8');
$sql1 = 'SELECT * FROM players_data WHERE sum_name = "' . $formatedUserName1.'"';
$result1 = $conn->query($sql1);
if($result1->num_rows > 0) {
while ($row1 = $result1->fetch_assoc()) {
$GLOBALS['summonerData1'] = unserialize($row1['summoner_info']);
}
} else {
storeData($conn, $apiKey, $playerleagueNameSummoner, 'players_data');
header("Refresh:0; url=leaguesprofile1.php?userName=".$_GET['userName']."");
}
} else {
}
$sumiconid1 = $summonerData1->profileIconId;
$index++;
echo '<div class="stats-data stats-row loser" data-ladder_id="'.$playerleagueId.'" data-ladderdivison_id="'.$playerleagueNameSummonerDivison.'" data-promos1or2="'.$miniSeriesdatayesnodata.'">
<div class="table-cell rank">'.$index.'</div>
<div class="table-cell change-selected">
<a href="profile2.php?userName='.$playerleagueNameSummoner .'">
<div style="display: table;">
<div style="display: table-row;">
<div class="table-cell-2">
<div class="summoner-icon" style="background-image: url(http://ddragon.leagueoflegends.com/cdn/6.24.1/img/profileicon/'.$sumiconid1 .'.png);"></div>
</div>
<div class="table-cell-2">'.$playerleagueNameSummoner .'</div>
</div>
</div>
</a>
</div>
<div class="table-cell">
<div style="display: inline-block;" original-title=""> ';
if($datazlistleague->isHotStreak == true){
echo '<img src="img/league/Hot_streak.png"/>';
} else if($datazlistleague->isHotStreak == false){
echo '<img src="img/league/streak_none.png"/>';
}
echo '</div><div style="display: inline-block;" original-title="">';
if($datazlistleague->isFreshBlood == true){
echo '<img src="img/league/Recruit.png"/>';
} else if($datazlistleague->isVeteran == true){
echo '<img src="img/league/Veteran.png"/>';
} else if ($datazlistleague->isFreshBlood == false && $datazlistleague->isVeteran == false){
echo '<img src="img/league/Recruit_none.png"/>';
}
echo '</div>
</div>
<div class="table-cell change-selected">'.$playerleagueNameSummonerWins.'</div>
<div class="table-cell change-selected">'.$playerleagueNameSummonerLosses.'</div>
<div class="table-cell change-selected">'.number_format((float)$playerleagueNameSummonerGamesWinRate, 1, '.', '').'%</div>
<div class="table-cell change-selected">';
echo $playerleagueNameSummonerLP.'LP';
echo '</div>
</div>';
}
}
?>
</div>
</div>
</div>
</main>
CODE - What it should do is depending if the data-attribute called "data-ladderdivison_id" is I then show when page I showen if it is V then show that data on page V but using a up and down button from 1 - 5 to change.
Thanks in advance
You'll need to look at the structure your data is in and determine fairly early on in the script which bit is the "current important" entry point, that would probably be an indexer into an array containing your leagues.
You can do this for example by passing a parameter via the url that you then pickup in the beginning of your script, or initialize to some predefined point (probably 0 for the first league).
// take the ?league=... from the url or set it to 0
$currentLeagueIndex = isset($_GET['league']) ? $_GET['league'] : 0;
then where you're rendering the buttons you can point to the current url with that index plus or minus one.
$hrefPrevious = $currentLeagueIndex-1 > -1 // bounds check for sanity
? 'my-url?league=' . ($currentLeagueIndex-1);
: 'javascript:void()';
$hrefNext = ($currentLeagueIndex+1) < count($allLeagues)
? 'my-url?league=' . ($currentLeagueIndex+1);
: 'javascript:void()';
I have button that displays a modal which contains many icons, and I want it when I click one of the images it will indicate that I have clicked it. But I don't have any idea how to implement it.
So far this is how my modal looks like.
My objective:To put an indicator that I have clicked it.
CODE
<div class="modal-body">
<div class="row">
<div class="col-lg-6 pull-left">
<?php
$tokenSql = mysql_query(" SELECT * FROM topplayer WHERE user_id = '$user_id' ");
$retToken = mysql_fetch_assoc($tokenSql);
$token = $retToken['token'];
echo ("<b>Tokens : $token </b><br>");
?>
</div>
<div class="col-lg-6 pull-right">
</div>
</div>
<div class="row ml">
<?php
$sendGiftSql = mysql_query("SELECT * FROM gifts WHERE isDelete = 'false' ORDER BY price ");
while($sendGift = mysql_fetch_assoc($sendGiftSql)){
$giftIMG = $sendGift['img_path'];
echo("
<div class='col-xs-4 mb'>
<br>
<img id='edgiftPhoto' class='center-block' alt='No image' src='$giftIMG' style='height:120px; width: 120px'/>
</div>
");
}
?>
</div>
Generic, super super super simple solution. No need for a plugin.
JS:
$('.modal-body').on('click','img',function(){
$(this).toggleClass('clicked');
})
CSS:
.clicked{
border:1px solid black;
//style it however you want
}
i'm doing a project for my school whereby i have to retrieve student works from database.
On my home page, i have preset 10 div to hold the data returned from query. I preset it because i only need to retrieve 10 data.
HTML
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
</div>
Then i use jquery to query to my php to get back 10 data and place onto my 10 div
Jquery
/* Home Page Autoload featured thumbnails based on computer viewport/mobile viewport
================================================== */
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/displayFeatThumbs.php",
success: function(data) {
// Display image thumbnail, caption & description of works onto each thumbnail div
$('.viewport-computer .img_thumb_holder img').each(function(index, element) {
// Work out the data to set
var imageUrl = "cms/" + data[index].links;
var captionHtml = "<span>" + data[index].caption + "<span class='spacer'></span><br/><span class='spacer'></span>" + data[index].title + "</span>"
// Now apply this to the elements
$(element).attr("src", imageUrl); // i must find a way to solve this
$(element).parent().css('background-image', 'url("'+imageUrl+'")');
$(element).next().html(captionHtml);
// push the caption & id into global variable array to be used on other functions easily
captionArray.push(data[index].caption);
idArray.push(data[index].id);
homeLinksArray.push(data[index].links);
homeTitleArray.push(data[index].title);
});
});
It's working fine since i loop through my preset div(10 of them) and then place the data into each div.. Now i need to do a search bar function, and it will return me ALL the results(more than 50), and i have to display all of them, now the problem is that i only preset 10divs, so my workflow is not good for this
so instead of my current
loop through 10 div > retrieve data and place on 10 div
i would like to
retrieve all data, for each data, append a new div and place it
i am not very good with php as i'm still a new learner so i'm stuck at this although i have the idea on how to do it. Can someone enlighten me on how i can loop through each data and append instead of my preset divs?
PHP
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links[] = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode($links);
} else {
echo "0 results";
}
?>
Solution is not to preset 50 divs or 10 divs in your UI.
Simply when you retrieve your result loop through all records and at the same time instead of populating your divs you create divs on the fly and insert data to it. When newly created divs are ready append them to your UI with some classes like 'new-data' or something to give a look that these records are somewhat new in your UI.
Assuming data represent your json returned by PHP and data is collection of all records here is one way to do it
for(i=0; i<data.length; i++)
{
$('<div class="col-lg-2 img_thumb_holder no-padding new-class">'
+'<img src="'+data[i].imgSrc+'" class="img_thumb">'
+'<h2 class="caption">'+data[i].author+'<br />'+data[i].description+'</h2>'
+'</div>').appendTo("ul#yourRecordHolderElemenet").slideDown("fast");
}
Exact solution might depend on your json returned by PHP untill you show your exact json response we won't be able to help you properly.
I won't recommend returning data with their html markup being returned from PHP as it would increase amount of data being transferred.
Since you already have the information in database, add them directly in HTML rather than making a ajax request.
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<?php
//You can get 10 records from database using 'limit 10' added to select query.
//Get data from database. I assume you have the data in a variable $datafromdb
foreach($datafromdb as $data){
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?=$data['author']?><br /><?=$data['description']?></h2>
</div>
<?php } ?>
</div>
Without writing complete code for you here is a step by step how you could do this
Create a database connection with mysqli or pdo
Select all records with a select query
Do a foreach on the resultset
Add one div in the foreach
PHP will add a div for each row in the select query
for example:
foreach($result->fetch_array() as $row) {
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?= $row['author'] ?><br /><?= $row['description'] ?></h2>
</div>
<?php
}
PHP Code should be :
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode(array('contents' => $links));
} else {
echo "0 results";
}
?>
notice single dimension $link array and an associative array to json_encode.
In jQuery, your success: can/will be :
success: function(data){
$.each(data.contents, function(ind, ele){
// ele.id is the id and etc... or ind.id. :D
});
}