0

I want to be able to make buttons to hide or show tables on my web page, rather than making a new function for each table Id like to just make one, that takes an argument name which will be the div ID of the table. The function works whwn I dont pass in an argument and hard code the solution but when I try passing in a string thats when it stops working.

I have tried creating a PHP variable and passing that, but all of it breaks the code. It seems like the function is not being called at all, because when I included an alert function it wasn't called.

Working Code

echo "<button onclick='myFunction()'>View La Liga</button>
    <div id='myDIV' style='display:none'>";

....

<script type="text/javascript">
  function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
    x.style.display = "none";
 }
}
</script>

Broken code

echo "<button onclick='myFunction('myDIV')'>View La Liga</button>
    <div id='myDIV' style='display:none'>";

....

<script type="text/javascript">
  function myFunction(y) {
    var x = document.getElementById(y);
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
    x.style.display = "none";
 }
}
</script>

This should allow me to just call the function with the div name rather than hard code it, but the function does not get called at all. I feel like I am making a simple mistake.

Marc-9
  • 145
  • 1
  • 9
  • See https://stackoverflow.com/questions/38739465/need-third-kind-of-quotation-marks-in-javascript – PM 77-1 Jul 18 '19 at 18:00

3 Answers3

1

You are using the same type of quotation mark twice because of the string in here:

'myFunction('myDIV')'

Change your code, replacing ' to " in the argument. Like this:

<button onclick='myFunction(\'myDIV\')'>View La Liga</button>
    <div id='myDIV' style='display:none'>
Azametzin
  • 5,223
  • 12
  • 28
  • 46
1

You need to escape the quotes around the id in the PHP echo call

echo "<button onclick='myFunction(\'myDIV\')'>View La Liga</button>
<div id='myDIV' style='display:none'>";
goudarziha
  • 327
  • 5
  • 20
1

You should escape the quotes, something like this:

echo '<button onclick="myFunction(\'myDIV\')">View La Liga</button>
    <div id="myDIV" style="display:none">';
Cosmin
  • 26
  • 4