How to print all elements by id (JS,PHP) - javascript

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!

Related

In JavaScript, how to hide / show a div by clicking on the icon that corresponds to it

I'm looking for a method in native JavaScript or jQuery to display a div by clicking on the icon that corresponds to it.
The icons are in a carousel that works with Owl Carousel 2
Icons and div are created dynamically on WordPress with an ACF Repeater Fields
Icons and div each have an ID :
For icons: img_1, img_2 ...
For blocs: div_1, div_2 ...
The icons carousel loop :
<?php $GLOBALS['img'] = 0;
if (have_rows('carrousel_icons')): ?>
<div id="owl-carousel-skills" class="owl-carousel-skills owl-theme col-12 col-sm-10">
<?php while (have_rows('carrousel_icons')): the_row();
$icon = get_sub_field('icon');
$GLOBALS['img']++;
?>
<div id="img_<?= $GLOBALS['img'] ?>" class="owl-carousel-skills-menu-item">
<img src="<?= $icon['url'] ?>" alt="<?= $icon['alt'] ?>">
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
ACF Repeater Fields Blocs :
<?php
$GLOBALS['div'] = 0;
$counter = 0;
if (have_rows('carrousel_icons')): ?>
<div class="col-12 col-sm-8 bloc_carousel_icons__txt">
<?php while (have_rows('carrousel_icons')): the_row();
$title = get_sub_field('title');
$txt = get_sub_field('txt');
$GLOBALS['div']++;
if ($counter) {
?>
<div id="div_<?= $GLOBALS['div'] ?>" class="inactive" style="display: none;">
<h3><?= $title ?></h3>
<?= $txt ?>
</div>
<?php continue; } ?>
<!-- first DIV -->
<div id="div_<?= $GLOBALS['div'] ?>" class="active" style="display: block;">
<h3><?= $title ?></h3>
<?= $txt ?>
</div>
<?php $counter++;
endwhile; ?>
</div>
<?php endif; ?>
Link to see a screenshot
I tested something but it only shows / hides all the div at once by clicking on any icon :
$(function(){
var $allBlocks = $(".bloc_carousel_icones__textes > div");
var id = this.id, itemId = ".bloc_carousel_icones__textes > #div_" + id;
$(document.body).on("click", "div.owl-carousel-competences-menu-item", function (evt) {
var id = this.id, itemId = ".bloc_carousel_icones__textes > #div_" + id;
$allBlocks.not($('.hidden').fadeToggle()).hide();
});
});
I have no idea how to do this, anyone have an idea?
Thanks in advance !
You can do it like this: Add a click() event handler for all images that have an id that starts with img_, get the number of this id with substr and toggle the corresponding div.
$(document).ready(function() {
$("img[id^='img_']").on("click", function() {
let id = $(this).attr("id").substr(4);
$("#div_" + id).fadeToggle();
});
})
Update: As asked in the comment, there's a solution needed to deactivate the previously active <div> when a new <div> gets activated. This can be done as follows:
$(document).ready(function() {
$("img[id^='img_']").on("click", function() {
let id = $(this).attr("id").substr(4);
if ($("div[id^='div_']").not($("#div_" + id)).is(":visible")) {
$("div[id^='div_']").not($("#div_" + id)).fadeToggle();
}
$("#div_" + id).fadeToggle();
});
})
div[id^='div_'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img_1" src="https://dummyimage.com/50x50/000000/ffffff&text=1" />
<img id="img_2" src="https://dummyimage.com/50x50/cecece/000000&text=2" />
<div id="div_1">
div 1
</div>
<div id="div_2">
div 2
</div>

Content of innerHTML is "undefined"

I never had this problem before, but now working with PHP when I try to edit the content of a div with the id of a product taken directly from it's id in the database like this (both separaed in two foreach getting their current correct IDs) because I need them separated so when I can change the content, I can modify it so I can make the second DIV display: none by default and after clicking the first one making it display: inline:
<div id="h<?php echo $obra['id'] ?>" onClick="display()"> </div> // Getting ID h + 84 (h84) this time
<div id="<?php echo $obra['id'] ?>"> TEST TEXT</div> // Getting ID 84 this time)
And the function is:
function display() {
var result = document.getElementById("84").innerHTML;
result.innerHTML = "test";
alert(result);
}
Now, when I click the first DIV, it should get the content of the div with ID 84, which is "TEST TEXT", and then change it for "test" and change the content which I see in the browser and after that, alert with the new result value, but the content doesn't change and the alert shows me TEST TEXT.
Here is the full relevant code if needed:
<div class="row m-0">
<div class="accordion pl-0 col-4 text-center">
<?php if ( count($cuadros) == 0) { ?>
<p class="text-center mt-3">No hay cuadros registrados.</p>
<?php } else {
$cont = 0;
foreach ( $cuadros as $obra ) { ?>
<div class="card border-top-0 border-left-0 rounded-0 p-0">
<div class="card-header border-0" id="h<?php echo $obra['id'] /* it gets value "84" */ ?>" onClick="display()">
<h5 class="mb-0">
<?php echo $obra['nombreObras']; ?>
</h5>
</div>
</div>
<?php $cont++; } ?>
</div>
<?php foreach ( $cuadros as $obra ) { ?>
<div class="col-4 hidden" id="<?php echo $obra['id'] /* It gets value "84" */ ?>">
TEST TEXT
</div>
<?php } ?>
<?php } ?>
</div>
And a screenshot of what happens (note that the change should be reflected in the alert, which is not)
Thank you!
You are performing innerHTML agin. So it will return error. Remove innerHTML from result
function display() {
var result = document.getElementById("84");
result.innerHTML = "test";
alert(result);
}

Using a jQuery function with a PHP while loop

I'm creating a website for a client, but I'm primarily a front-end developer. I had to create a while loop (which works just fine) to build a gallery. The client wants a before/after display on the gallery. I elected to use the TwentyTwo jQuery plugin. However, I am having an issue. It is only displaying the first container, which displays just fine.
The necessary jQuery, inline , and css files are displayed on that page linked above. I am using bootstrap as a framework. Here is my code:
$(window).load(function() {
$("#container1").twentytwenty();
});
<div class="row">
<div class="col-lg-12">
<h2><span class="color">Our Gallery</span> </h2>
<?php
//Selects all images
$sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery ORDER BY postDate DESC") or die($GLOBALS['gmysqli']->error);
while ($row = $sql->fetch_assoc()) {
$image = $row["image"];
?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container1" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php } ?>
</div>
</div>
The problem here is the duplicate ID you generating in the php loop. This results in invalid html and can cause problems when using it as a selector.
You can switch to using a class selector:
$(document).ready(function(){
$(".twentytwenty-container").twentytwenty();
});
I updated your ready handler to the recommend structure. Or for the shorthand:
$(function() {
$(".twentytwenty-container").twentytwenty();
});
When using the class selector you can get rid of the ID in the HTML element
If you want to stick to the ID you can add a iteration variable to your loop and use the attribute selector:
$(function() {
$( "div[id^='container-']" ).twentytwenty();
});
<?php
$i = 0;
while($row = $sql->fetch_assoc()) {
$image = $row["image"]; ?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container-<?php echo $i; ?>" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php
$i++;
} ?>
try without order by statement.
Example:
<div class="row">
<div class="col-lg-12">
<h2><span class="color">Our Gallery</span> </h2>
<?php
//Selects all images
$sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery") or die($GLOBALS['gmysqli']->error);
while($row = $sql->fetch_assoc())
{ $image = $row["image"]; ?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container1" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php } ?>
</div>
</div>
If you could share how you database are filled out could more easy to help you.
And the project link.
I hope helped you out anyway.

PHP equivalent to the JavaScript parentNode Property

I'd like to check the id of the parent element, to display either the big or the small version of an image.
<div id="content">
<?php include 'test.php';?>
</div>
<div id="sidebar">
<?php include 'test.php';?>
</div>
In test.php, an if-statement checks if the parent has the demanded id.
Is there a way to get the parentnode-id without JavaScript?
No. PHP do nothing with the rendered page.
But why don't you create a function and call that with parameters?
include 'test.php'
?>
<div id="content">
<?php showImage(); ?>
</div>
<div id="sidebar">
<?php showImage(true); ?>
</div>
<?php
And in test.php
function showImage($smallImage = false) {
if (!$smallImage) {
echo '<img src="path/to/bigimage" alt="" />';
} else {
echo '<img src="path/to/smallimage" alt="" />';
}
}
Or there are an alternative way. Set a variable before you include your file, and you can set an if condition in your test.php when you want to show the image.
<div id="content">
<?php
$parentNode = 'content';
include 'test.php'
?>
</div>
<div id="sidebar">
<?php
$parentNode = 'sidebar';
include 'test.php'
?>
</div>

jquery .attr() returning as undefined

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');

Categories

Resources