JavaScript onclick only works once and doesn't update - javascript

I have the following php code:
foreach ($facility_names as $name)
{
echo '<div class="row facility-name">';
echo '<button id="facilityNameLeft" class="btn btn-default btn-fill btn-menu" onclick="javascript:showDetails()">'.$name.'</button>';
echo '</div>';
}
<h1 id="facilityNameRight">Aquatics Centre</h1>
That should simply show a button inside a div for every $name (right?).
And this piece of javascript:
function showDetails() {
var facilityName = document.getElementById("facilityNameLeft").innerHTML;
document.getElementById("facilityNameRight").innerHTML = facilityName;
}
Now, I am new to javascript, but I can't figure out why the onclick only works once before I have to reload the page and why it only updates the innerHTML of the h1 tag with the value of the first $name (no matter which of the buttons I press).

Related

How to make a div refresh?

So this is my button div inside a PHP function called getDetails().
<div class='detail_cart'>
<a href='detail.php?add_cart=$prod_id'>
<button id='detail_button_add'>Add to cart</button>
</a>
</div>
Based on ip address, it counts how many products you've added in the cart and display them to my shop cart icon.
Every time the button is pressed it adds the product into a database but i need refresh page in order to see the updated count.
echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
echo "</div>";
I tried to fix but no chance..
<script type= "text/javascript">
$(document).ready(function(){
$("#detail_button_add").bind("click",function(){
$("#total_cart").load("header.php");
});
});
</script>
"header.php" is the header section of my PHP.
You need to add an clear div with an span inside. You will get the data from an API in this case your header.php that returns 1,2 or any number and that will be displayed.
Your header.php
echo mysqli_num_rows($run_cart);
http_response_code(200);
exit;
<div id="total_cart">
<span id="total_cart_num"></span>
</div>
<div>
<a href="detail.php?add_cart=<?=$prod_id ?>">
<button id="detail_button_add">Add to cart</button>
</a>
</div>
<script>
document.querySelector("#detail_button_add").addEventListener("click", function(){
refreshCart();
});
function refreshCart(){
const xhr = new XMLHttpRequest();
// Add link to your Site that returns the count
xhr.open("GET", "header.php"); // Header returns Like 1,2,3 or any Number
xhr.addEventListener("load", function(){
if(this.status == 200){
document.querySelector("#total_cart_num").innerHTML = this.responseText;
} else {
alert("An error as been triggered!");
}
});
xhr.send();
}
</script>
If you mean that this is header.php:
echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
echo "</div>";
and you do this:
$("#total_cart").load("header.php");
the result would be:
<div id ='total_cart'>
{content from header.php}
</div>
e.g.
<div id ='total_cart'>
<div id ='total_cart'>
{count of cart}
</div>
</div>
The solution is to skip the creation of div in the header.php:
(create that div elsewhere)
//remove echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
//remove echo "</div>";
If you don't get your click event to work, you might need to use on("click"... instead of bind("click"...
(on also works on dynamically created html elements (with content))
$(document).ready(function(){
$("#detail_button_add").on("click",function(){
//This header.php should NOT include the actual html-element (div) jsut the
//content you want INSIDE the htm-element with id #total_cart
$("#total_cart").load("header.php");
});
});
Another thing with your first code-snippet is that your link won't work:
<a href='detail.php?add_cart=$prod_id'>
It should be (taking for granted you have the code in a php-file)
<a href='detail.php?add_cart=<?php echo $prod_id;?>'>

Javascript gets only the first id from a foreach loop. Why?

I use a foreach loop to get some tabs with different id's. This way I get tabs with ids tab1, tab2, tab3, etc. Than, when I want to get the id of each tab using javascript, it returns only the id of the first tab and uses this for all tabs. It does not loop as php do. Why?
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div id="divid" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var dividvalue = document.getElementById('divid').innerHTML;
alert(dividvalue);
});
</script>
<?php
}
?>
Change the id in your HTML to class, and use getElementsByClassName instead of getElementById your in JavaScript.
Your div:
<div class="divid"> <!-- etc -->
and your JS..
var dividvalue = document.getElementsByClassName('divid')[0].innerHTML;
Also consider changing divid to divclass for consistency's sake.
Full edited code:
<script>
var i = 0;
</script>
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div class="divclass" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var divclassvalue = document.getElementsByClassName('divclass')[i].innerHTML;
alert(divclassvalue);
i++;
});
</script>
<?php
}
?>

How do I trigger this hover function each time a new image has focus?

How can I hide all the images in a recordset except the image with the mouse hover on?
Images are displayed from the database and I am trying to manipulate how the images respond when a user hovers on any particular image.
Based on what I have read here on stackoverflow I came up with the following that actually works but with one limitation
On page load it works fine but once you start moving from image to image nothing happens.
I want only the active or image with hover to show while hiding the rest.
$(document).ready(function() {
$('.teamDisplay').hover(function(){
var infoFont = $(".imageDiv")
var $imgLink = $(this).children(infoFont).attr("data-imgPath");
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOff');
$(this).addClass('imageDivOn');
}, function(){
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOn');
$(this).addClass('imageDivOff');
});
});
I am also using css to show or hide the images but the hover function appears to work just once on page load.
How do I trigger this hover function each time a new image has focus?
This is the website with the feature I hope to replicate
UPDATE
The html code
`<div class="memberPicBg">
<?php do { ?>
<span class="teamDisplay">
<?php
// Show If File Exists (region1)
if (tNG_fileExists("../images/team/", "{members.tmemberphoto}")) {
?>
<span class="imageDiv" data-imgPath="../images/team/<?php echo $row_members['tmemberphoto']; ?>">
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span><br /><br />
<img src="../images/team/<?php echo $row_members['tmemberphoto']; ?>" alt="<?php echo my_meta_description($row_members['tmember'],6); ?>" border="0" /> </span>
<?php
// else File Exists (region1)
} else { ?>
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span>
<?php }
// EndIf File Exists (region1)
?>
</span>
<?php } while ($row_members = mysql_fetch_assoc($members)); ?>
</div>`
NB: apologising if I am not clear enough.

jQuery loop through set of divs, one at a time

I am building a wordpress onboarding plugin.
I have an array that contains the content for each step of onboarding process, then a function that outputs each step in it's own container, with it's own class:
static function action_build_steps() {
$items = Onboarding_Dashboard::dashboard_onboarding_content();
$output = '';
foreach ($items as $step => $item) {
// Classes
$step_class = array();
$step_class[] = str_replace("-", "", $step);
$step_class[] = (isset($item['class']) ? $item['class'] : NULL);
$step_class = implode( ' ', $step_class );
echo '<div id="onboarding_steps_container" class="'.$step_class.' onboarding-'.Onboarding_Setup::onboarding_slug().'" style="left:'.$item['left'].'; top:'.$item['top'].'; width:'.$item['width'].';">';
echo '<div class="onboarding_steps">';
echo '<h2>'.$item['title'].'</h2>';
echo '<p>'.$item['content'].'</p>';
if(isset($item['css_arrow'])) {
echo '<div class="arrow_'.$item['css_arrow'].'"></div>';
}
echo '</div>';
echo '<div class="button_holder">';
if (($item['show-prev'])=='true') {
echo '<button id="prev" class="'.$step_class.'"><i class="fa fa-chevron-left"></i> PREV</button>';
}
if(($item['show-next'])=='true') {
echo '<button onboarding_stage="dashboard" id="next" class="'.$step_class.'">NEXT <i class="fa fa-chevron-right"></i></button>';
}
echo '</div>';
echo '</div>';
}
return $output;
}
This results in showing ALL steps at once, however, the plan is to show one step at a time, and when the user clicks "Next" or "Prev" they see the next or previous step.
I know I need to do this using jQuery but can't think how I will do it, mainly because I have a dynamic number of steps - it's not a set number.
So far, I have just hidden all steps using this script:
jQuery(function($) {
$('.onboarding-<?php echo Onboarding_Setup::onboarding_slug(); ?>').hide();
});
My outputted html looks a bit like this (I'll take out the content)
<div id="onboarding_steps_container" class="step1 onboarding-dashboard" style="left:50%; top:320px; width:500px;">
<div class="button_holder">
<button onboarding_stage="dashboard" id="prev" class="step1 ">NEXT <i class="fa fa-chevron-right"></i></button>
<button onboarding_stage="dashboard" id="next" class="step1 ">NEXT <i class="fa fa-chevron-right"></i></button>
</div>
</div>
<div id="onboarding_steps_container" class="step2 onboarding-dashboard" style="left:50%; top:320px; width:500px;">
<div class="button_holder">
<button onboarding_stage="dashboard" id="prev" class="step2 ">NEXT <i class="fa fa-chevron-right"></i></button>
<button onboarding_stage="dashboard" id="next" class="step2 ">NEXT <i class="fa fa-chevron-right"></i></button>
</div>
</div>
Where you see the word 'dashboard' in the script above, that is also dynamically added depending on the page the user is on. Also, the first step doesn't have a previous button, and the last step doesn't have a next button (they do in my code above, but just for demonstration)
How would I iterate through each step, 1 at a time, hideing the previous step, then showing the next?
UPDATE:
Here is what I've managed to come up with so far:
jQuery(function($) {
var index = 0;
$(function() {
$('.onboarding_steps_container:not(:first)').hide();
$('#next').click(function() {
if (($('.onboarding_steps_container').length - 1) >= index) {
$('.onboarding_steps_container:eq(' + index + ')').hide();
index++;
$('.onboarding_steps_container:eq(' + index + ')').show();
}
});
$('#prev').click(function() {
if (index != 0) {
$('.onboarding_steps_container:eq(' + index + ')').hide();
index--;
$('.onboarding_steps_container:eq(' + index + ')').show();
}
});
});
I think my issue is that each step has a different button (even though the ID is the same a referenced in my script)
});
However, this only works for the first button click, no others
Here's a JSFiddle showing my situation:
https://jsfiddle.net/fwysy2rr/
Make a function in javascript call onclick on next btn
var current_div =1;
function showDiv(var i){
//first hide all div having class onboarding-
//show next div
$(".step"+current_div+1 + "onboarding-dashboard");
//set current div
current_div +=1 ;
}

PHP echo statement within getElementByID div tag

I've currently got a form which i use from Gravity forms, here is my html code
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">SPECIFY PRODUCT</button>
<div id="myDropdown_<?php echo get_the_ID(); ?>" class="dropdown-content">
<?php gravity_form( 1, false, false, false, '', true ); ?>
</div>
</div>
as you can see i'm echoing the product ID from woocommerce to give a different div id dependent on which product the user clicks on. This works fine.
Although, now when i create javascript function :
function myFunction() {
document.getElementById("myDropdown_<?php echo get_the_ID(); ?>").classList.toggle("show");
}
how can I pull through 'get_the_ID' like i have in the html code so it can dropdown my form in accordance to the product selected?
You can take a look at it here : http://www.ctagroup.com.au/cta-group-home/products/tactile-guidance/suresteel/suresteel-classic/
Any help would be greatly appreciated.
Regards
It is because the "myDropdown_<?php echo get_the_ID(); ?>" part is treated as string not PHP code.
Try this way:
<script>
var theId = "<?php echo get_the_ID(); ?>";
function myFunction() {
document.getElementById("myDropdown_" + theId).classList.toggle("show");
}
</script>
You always can try to generate JS code by PHP instead.
Of course in case, if the attempts to solve the problem have been unsuccessful.
Don't see any problems with this "technique".

Categories

Resources