Content of innerHTML is "undefined" - javascript

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

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>

Create popup boxes for each row in mySQL

So I have the following code:
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$links = $rows['links'];
$linksArray = explode(',', $links);
if ($links == ""){
unset($linksArray);
}
?>
//LINK TO ACTIVATE POPUP BOX
<a href="#popup1">
<div class="newsBox">
<h2><?php echo $rows['title'] ?></h2>
<h4>Posted # <?php echo $rows['date'] ?></h4>
<?php
if (!empty($linksArray)){
?>
<span><i>Links associated with this post:</i>
<? } ?>
<?php
foreach($linksArray as $link) {
?>Here</span>
<?
}
?>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Here i am</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php echo $rows['news'] ?>
</div>
</div>
</div>
</div>
<br>
</a>
<?php
}
mysql_close();
?>
For each row identified by my query, it links it to a popup box. However all the rows being outputted activate the same popup box. My question is how to create my popup box such that each row being outputted is linked to different popup boxes, if that makes sense. Such as the first row, when linked opens a popup box with that row's info. The next row after, when linked opens a popup box with that row's info, and so on. (I guess maybe like a dynamic popup box?)
Add a counter in your loop and where you have your <a href="#popup1"> and <div id="popup1" class="overlay"> add in the counter variable like <a href="#popup<?php echo $x ?>"> and <div id="popup<?php echo $x ?>" class="overlay">
This would make your popup id unique.

Show a number of items on clicking show more button

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>

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

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!

How to make an image inside a modal clickable

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
}

Categories

Resources