Speakmore Speakmore - 1 month ago 10
CSS Question

Toggle Visibility of my Divs in JavaScript

I have coded a button and some javascript that I thought would work with the button but it's currently not working. So I'm looking for some help to correct my code.

Button:
<label class="switch">
<input type="checkbox" class="whichStore"></input>
<div class="slider round"></div>
</label>

Divs that I want to swap the prices on when the button is clicked:
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<p>Item:</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-6 col-xs-6">
<p>Item Placeholder</p>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2" class="priceA">
<p><span class="money">$</span>9.99</p>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2" class="priceB" style="display: none">
<p><span class="money">$</span>8.87</p>
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-2"></div>
</div>

My script:
<script>
document.getElementsByClassName("whichStore").onchange = function() {
var priceA = document.getElementsByClassName("salaryA");
var priceB = document.getElementsByClassName("salaryB");
if (priceA.style.display == "none") {
document.getElementsByClassName("priceA").style.display = "";
document.getElementsByClassNames("priceB").style.display = "none";
} else if (priceB.style.display == "none") {
document.getElementsByClassName("priceA").style.display = "none";
document.getElementsByClassName("priceB").style.display = "";
}
}
</script>


I have my div in a modal, so when I click a word the modal pops up with the table in it.
Each row of the table will have an Item Category and then the Item Name, example being
Toiletries: Toilet Paper
and then the price at whichever store. So if Walmart's price is $0.99 a roll and Target's is $0.75

When the modal is displayed, it'll start on Walmart's price (whatever that may be), and then if I click the button, it'll change the price to Target's price, hiding Walmart's. Then if I click the button again, it toggles back to Walmart's price.

Answer

You can use the jQuery toggle() method for this.

Add this to the head of your html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

then use a separate script to make the button work. Something like this for :

<script>
$(document).ready(function(){
$("button").click(function(){
    $("#test").toggle();
  });
});
</script>

There is an example below.

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_toggle