onclick even not working - javascript

in the code below on clicking the button corresponding price should be displayed and the click here text shud hide but it doesn't work nothing happens
<body>
<?php $itemprice = array("$10","$3","$5","$7");?>
<?php $len = count($itemprice);
$i=0;
?>
<div class= "gallery">
<?php while ($i<$len):?>
<div class="index">
<div class="clickbtn">
<a id="hiddenprice-<?php echo $i; ?>" href="http://www.bookurl.com" onclick="show_price(<?php echo $i; ?>)" target="_blank">
Click Here to reveal price <?php echo $itemprice[$i]; ?>
</a>
<a id="revealedprice-<?php echo $i; ?>" style="display:none;" href="http://www.bookurl.com"><?php echo $itemprice[$i]; ?></a>
</div>
</div>
<?php $i++;endwhile;
?>
<script>
function show_price(<?php echo $i; ?>) {
document.getElementById('revealedprice-<?php echo $i; ?>').style.display = '';
document.getElementById('hiddenprice-<?php echo $i; ?>').style.display = 'none';
}
</script>
</div>
</body>
u can see the outcome live at http://myproject.byethost7.com/test1.php

You have a mess between the PHP code and javascript code.
Also, it's not clear what you're trying to do with that anchor. If you have a href defined, the user will navigate to that url, the onclick code is irrelevant in your case unless you cancel the navigation.
It seems to me that you want to do this. Take into account that you can't control 100% if the url will be opened on a new window or a new tab.
HTML
<a id="hiddenprice-<?php echo $i; ?>" href="#" onclick="show_price(<?php echo $i; ?>)">
Click Here to reveal price <?php echo $itemprice[$i]; ?>
</a>
JS
<script>
function show_price(num) {
document.getElementById('revealedprice-' + num).style.display = '';
document.getElementById('hiddenprice-' + num).style.display = 'none';
window.open("http://www.bookurl.com");
return false;
}
</script>
Notice num on show_price, the added window.open and the return false to cancel the default anchor behavior (navigate to the href)

Do not trust everything you see :)
What would append if you use the previous answer, without understanding it? Try, but you're going to have a surprise.
Explanations.
<a id="hiddenprice-5" href="http://www.bookurl.com" onclick="show_price(5)" target="_blank">
Click Here to reveal price 52
</a>
Show_price function is now well defined. But. But you are using a link - the a tag -. When you're going to click, the effect would be fine, but there is still the redirection: the user would never see the revealed price.
In order to avoid this "kiss cool effect", you must use another tag than a, or add a return false; to your show_price function.

Related

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

jQuery addClass within a foreach loop

I have a few foreach loops with a trigger and a content div. The intent is for the trigger to be clicked, then addClass to content div, making it visible on screen.
foreach markup
<?php foreach( $posts as $post ) : ?>
<a class="slide-trigger" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
<span>
<?php
$speakers = get_field('speakers');
?>
<?php if( $speakers ): ?>
<ul class="flat">
<?php foreach( $speakers as $speaker ): ?>
<li>
<a href="<?php echo get_permalink( $speaker->ID ); ?>">
<?php echo get_the_title( $speaker->ID ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</span>
<div class="slide" id="loc<?php echo $post->ID;?>">
<div class="close"></div>
<?php echo $post->post_title;?>
<?php echo $post->post_content;?>
</div>
<?php endforeach; ?>
jQuery
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id^='loc']").addClass("open");
})
$(".close").click(function(){
$(".slide").removeClass("open");
});
What I'm looking for is each slide-toggle to trigger it's slide.
Any thoughts?
The ID is in the href, so just grab it and remove the #loc prefix, then you can select the corresponding slide to open. Also this way, the startsWith selector is no longer required.
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id='loc" + this.href.replace('#loc', '') + "']").addClass("open");
})
Having to parse out the ID, then concatenate like this seems a bit hacky. It would be nicer to use data-* attributes.
Link:
<a class="slide-trigger" data-id="<?php echo $post->ID;?>" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
Slide:
<div class="slide" data-id="<?php echo $post->ID;?>" id="loc<?php echo $post->ID;?>">
jQuery:
$(".slide-toggle[data-id]").click(function(e){
e.preventDefault();
$(".slide[data-id=" + $(this).data('id') + "]").addClass("open");
})
#MrCode had two great solutions to this. The data-id method is a bit more elegant and what I went with.
Note, the $post->ID is a number which just won't work as an id= - https://css-tricks.com/ids-cannot-start-with-a-number/ - and was causing the issue where things just wouldn't work.
The answer; follow #MrCode's method of using a data attribute. It's elegant and works great w/ the loop.

Multiple Expand/Collapse Bootstrap buttons in a PHP foreach loop

My code is almost working, with one issue that I'm having a hard time fixing. Here is some code that I have simplified.
<?php for($counter = 0; $counter < 5; $counter++)
{
?>
<button type="button" id="<?php echo 'change_button_label_' . $counter?>" data-toggle="collapse" data-target="<?php echo '#button_number_' . $counter?>" class="btn btn-warning"><span class="glyphicon glyphicon-chevron-down"></span>Expand</button>
<div id="<?php echo 'button_number_' . $counter?>" class="collapse">
This gets collapsed #<?php echo "$counter"; ?>
</div>
<script>
$('<?php echo "#change_button_label_" . $counter?>').click(function () {
if($('button span').hasClass('glyphicon-chevron-up'))
{
$('<?php echo "#change_button_label_" . $counter?>').html('<span class="glyphicon glyphicon-chevron-down"></span>Expand');
}
else
{
$('<?php echo "#change_button_label_" . $counter?>').html('<span class="glyphicon glyphicon-chevron-up"></span>Collapse');
}
});
</script>
<?php
}
?>
If I try to click 1 or more buttons, they work in the sense that each will expand/collapse and reveal/hide its relevant content as expected.
However, only the 1st button that is clicked (and it doesn't matter which one is clicked 1st) will have its text and glyphicon changed from "expand" to "collapse." All of the other buttons will continue to say "expand" regardless of if they are actually expanded or collapsed.
I'm hoping someone can help me figure out how to fix it so that the other buttons will toggle their text correctly when they are clicked. I don't mind gutting my attempted code above if needed.
Actual output:
Expected output:
The text on each button should look like the first one after they've been clicked. The expand/collapse feature is already working for each button.
Generated HTML/CSS output:
https://gist.github.com/bryanjamesmiller/c14e623152ab9b5f9246
Thank you in advance!
Take your script block out of the PHP for loop and bind to the button element itself, rather than the button ID:
<?php for($counter = 0; $counter < 5; $counter++)
{
?>
<button type="button" class="btn btn-danger" id="<?php echo 'change_button_label_' . $counter ?>">DISLIKES<span class="glyphicon glyphicon-thumbs-down"></span></button>
<?php
}
?>
<script>
$(document).ready(function(){
$('button').click(function() {
var $button = $(this),
test = $button.text() === 'DISLIKES';
if(test)
{
$button.text('LIKE');
test=false;
}
else
{
$button.text('DISLIKES');
test=true;
}
});
});
</script>
This is pretty basic and will just change the button text. To toggle the icon as well you'd just need to do something like:
$button.addClass('like-class');
or
$button.removeClass('dislike-class');
In the appropriate if block
Check out this fiddle to see it in action
change
if($('button span').hasClass('glyphicon-chevron-up'))
to
if($('button#<?php echo 'change_button_label_' . $counter?> span').hasClass('glyphicon-chevron-up'))
you are done !

How to detect a product attribute with Javascript? (Magento)

I have a working solution to a problem where we're replacing all 'Add to Cart' buttons with 'In Store Only' buttons for items that are only available in store. I'm using PHP to detect the attribute and produce HTML that replaces the button.
<?php
//Checks if the "Disable Add to Cart" variable is set to 'Yes':
if(($_product->getAttributeText('No_cart_button')) == "Yes"){
//If set to Yes, tell PHP what to output:
echo "This Product is not available online, please call our representative if you wish to purchase this.";
}
//If set as No, then show the 'add to cart box' as usual.
else {
?>
<?php if (!$this->hasOptions()):?>
<div class="add-to-box">
<?php if($_product->isSaleable()): ?>
<?php echo $this->getChildHtml('addtocart') ?>
<?php if( $this->helper('wishlist')->isAllow() || $_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product)): ?>
<span class="or"><?php echo $this->__('OR') ?></span>
<?php endif; ?>
<?php endif; ?>
<?php echo $this->getChildHtml('addto') ?>
</div>
<?php echo $this->getChildHtml('extra_buttons') ?>
<?php elseif (!$_product->isSaleable()): ?>
<div class="add-to-box">
<?php echo $this->getChildHtml('addto') ?>
</div>
<?php endif; ?>
<?php
}
?>
I've been told that Javascript would be a less intrusive way of doing achieving the same result. Am I right in assuming that you would use PHP to insert a class or id into the HTML element and do the rest with Javascript? Detect the id or class --> generate the replacement button?
Thanks!

Trying to display data shown depending on what users click

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>
Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.
Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>
Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>
You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Categories