-3

I'm working in wordpress with the woocommerce plugin where I wan't to show two different prices on my products.

One as default that is shown as the user gets to the page and one that's shown when the user clicks a button. If he clicks the same button again the previous price should show again. And so on.

So some type of check of what is shown on the page, which could be done in JQuery I guess, but is there any other way? I tried a bit with JQuery but have a bit of problems using it with woocommerce.

<?php
$incl = $product->get_price_including_tax();?>

<p id="excl" class="price"><?php echo $product->get_price_excluding_tax();?> excl.</p>

<button type="button" onclick="document.getElementById('excl').innerHTML = <?php echo $incl;?>">Click Me!</button>

That does the one way around but needs the previous mentioned check in order to be used the other way around again.

And a extra question: those incl and excl tax call ruin the settings done in the admin end with the formatting of prices. So 6.000,00 for instant becomes 6000. I tried woocommerce_price which works but is deprecated. Is there a similar function to do that? Can't find anything in the documentation.

gerre
  • 155
  • 1
  • 11

2 Answers2

2

Use ternary operator, condition ? expr1 : expr2

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement[Reference]

Note: Do not mix-up your logic in markup. You should have a separate function for that.

<p id="excl" class="price">100</p>
<button type="button" onclick="document.getElementById('excl').innerHTML=document.getElementById('excl').innerHTML=='500'?'100':'500'">Click Me!</button>
Rayon
  • 36,219
  • 4
  • 49
  • 76
2

I would write them both to DOM and use toggleClass() from jQuery

<?php
$incl = $product->get_price_including_tax();?>
<div class="mycont">
    <p id="excl" class="price excl"><?php echo $product->get_price_excluding_tax();?> excl.</p>
    <p id="incl" class="price incl"><?php echo $incl;?> excl.</p>
</div>
<button type="button">Click Me!</button>

With following CSS:

.mycont > .price.incl {display: none}
.mycont.show_incl > .price.incl {display: block}
.mycont.show_incl > .price.excl {display: none}

And jQuery:

$('button').on('click', function(){
    $('.mycont').toggleClass('show_incl');
});

Fiddle Here

If you want to do it in pure javascript, I would suggest to call a function onClick event on button, and toggle class like stated here

Community
  • 1
  • 1
Yuri
  • 3,082
  • 3
  • 28
  • 47
  • Yeah that looks like something i imagined. But JQuery won't work. I can see in the source code that it's being loaded to the page but the code is just being treated as regular text anyway. – gerre Apr 20 '16 at 10:27
  • Thanks for the answer. I managed to get the jquery working and ended up with something similar to this. – gerre Apr 20 '16 at 12:19