-2

Hi I am trying the code below on a php page. I keep getting syntax error due to the single quotes around the parameter 'London' of the function openCity() shown below.

echo '<button class="tablinks" onclick="openCity(event, 'London')">London</button>';

If I remove the single quotes covering 'London' and add double quotes there, the function doesn't work as expected. What am I not seeing? Is there a way to fix this?

The openCity() javacript function is shown below.

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
'''


What I am trying to do is when a user clicks the button, it shows a block of elements (Like a tabs).

1 Answers1

-1

You are not escaping the quotes in your 'London' string, inside your echo statement. You need to use backslashes ( \ ) to prevent that.

echo '<button class="tablinks" onclick="openCity(event, \'London\')">London</button>';

If not escaped, your code will think the string finished at the first quote.

Nicolas
  • 8,077
  • 4
  • 21
  • 51