lcunning lcunning - 17 days ago 5
Javascript Question

Javascript - populate a div with content from a hidden div using click buttons

I need some help. As you will see in my fiddle, I am attempting to use buttons to populate a single container div with content from multiple hidden divs, depending on which button is clicked. The problem I am having is, I don't know how to access the actual content in the hidden divs to populate the container div. As of now, I am using the id attributes for the hidden divs to demonstrate which div content I would like to display in the container.

I've seen a few other posts with link

<a>
attributes referencing hidden content, but none so far using a button element with click functionality to change div content.

Thanks so much in advance for your help. I'm sure you can understand... it's keeping me awake at night. ha!



jQuery(function ($) {
$('#button1').click(function () {
$('#info').empty();
$('#info').prepend('#option1');
});

$('#button2').click(function () {
$('#info').empty();
$('#info').prepend('#option2');
});

$('#button3').click(function () {
$('#info').empty();
$('#info').prepend('#option3');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1">Button 1</button></li>
<li class="buttons"><button id="button2">Button 2</button></li>
<li class="buttons"><button id="button3">Button 3</button></li>
</ul>
</div>

<div id="info-div">
<div id="info"></div>
</div>

<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>





Here is my fiddle

Answer

Here's a version that uses jquery data attributes. It reduces the redundancy and complexity and can be configured easily.

<body>
        <div class="button-panel">
            <ul id="button-column" style="list-style: none;">
                <li class="buttons"><button id="button1" data-link="option1">Button 1</button></li>
                <li class="buttons"><button id="button2" data-link="option2">Button 2</button></li>
                <li class="buttons"><button id="button3" data-link="option3">Button 3</button></li>
            </ul>
        </div>
        <div id="info-div">
            <div id="info">

            </div>
        </div>
<div id="hiddenDivs" style="display:none;">
    <div class="info" id="option1">Box</div>
    <div class="info" id="option2">Google Drive</div>
    <div class="info" id="option3">Box</div>
</div>
</body>
<script>
   $('.buttons button').click(function (){
        $('#info').empty();
        $('#info').html($("#" + $(this).data('link')).html());
    });   
</script>

Example : https://jsfiddle.net/yvsu6qfw/3/