Reputation: 281
Lets got right to it!
I have done a PHP calculation that I wan't to display on my website. The tricky part is that I want the values to be displayed, ONE value each time the user clicks ONCE on a button. It doesn't matter what kind of button it is, I just wan't to display a value on every click. The total number of values are 8 (fixed length), and right now I have 4 arrays with 2 values in each. So every thing is done and saved, I'm just trying to display it, one at the time. If it is easier I could bunch them together to 1 array. Im trying to make a sort of display:none
vs display onclick
thingy, but it is only showing the first value on each click. Very grateful for tips and tricks! Will a kind of FORM
help me? By using input
instead?
This is what I've got:
HTML
<a href="#" class="modern" onClick="showhide('first', 'block'); return false" >Give me your value</a> <div id="first"><?php echo $team1[0];?></div> <div class="secound"><?php echo $team1[1];?></div> <div class="third"><?php echo $team2[0];?></div> <div class="fourth"><?php echo $team2[1];?></div> ...
Javascript
function showhide(divid, state){
document.getElementById(divid).style.display=state
}
...
Upvotes: 3
Views: 2091
Reputation: 6414
There are quite a number of different ways your could do this. Using a framework would make it much easier and effortlessly enable you to support multiple browsers, but assuming this isn't the goal and sticking to as much as what you have...
I've altered the PHP a bit:
<a href="#" id="team-next">Give me your value</a>
<div id="teams">
<div id="team-0"><?= $team[0][0] ?></div>
<div id="team-1"><?= $team[0][1] ?></div>
<div id="team-2"><?= $team[1][0] ?></div>
<div id="team-3"><?= $team[1][1] ?></div>
...
Notice that I have changed the id to a prefix team-
and an index 0 ... n, and the teams appear in a parent element with the id teams. I've also changed the array to a multidimensional array rather than multiple variables with numbers in them. This construct can be created by adding an array as an item of an array. Now the JavaScript (this should appear in a script tag after the above HTML):
// Initial index -1 (nothing displayed)
var current = -1;
// How many teams are there?
var count = document.getElementById("teams").children.length;
// The handler
function showNext() {
// A bit of modulus math, when it gets to the
// same value as the count it starts at 0 again
var next = (current + 1) % count;
// Hide the previous one, unless it is the first
if(current !== -1)
document.getElementById("team-" + current).removeAttribute("style");
// Show the next one
document.getElementById("team-" + next).style.display = "block";
// Update the current index
current = next;
}
// Bind the event listener
document.getElementById("team-next").addEventListener("click", showNext, false);
Upvotes: 4